关于自定义View,打算一直写一个系列,把整个流程自己也梳理一遍,和一些朋友一起从零学起。
相关文章:
《Android自定义View(一)(Paint和Canvas的基本使用)》
昨天公司让写一个关于百分比进度条,我一贯的尿性,开始网上看一些开源的控件,但是发现,尼玛代码太长了吧,写的好啰嗦啊,算了,自己写一个吧,于是开始陷入深深的思考之中,写出来之后和大家分享一下这个相对简单的自定义View。
一、效果图
二、代码及实现思路
/**
* 自定义进度条
* Created by Anonymous on 2016/7/5.
*/
public class CircleProgressView extends View {
//默认值
private int mMaxProgress = 100;
private int mProgress = 30;
private final int mCircleLineStrokeWidth = 8;
private final RectF mRectF;
private final Paint mPaint;
private final Context mContext;
private int Sweep = 1;
public CircleProgressView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mRectF = new RectF();
mPaint = new Paint();
}
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
int width = this.getWidth();
int height = this.getHeight();
if (width != height) {
int min = Math.min(width, height);
width = min;
height = min;
}
// 设置画笔相关属性
mPaint.setAntiAlias(true);
mPaint.setColor(getResources().getColor(R.color.grass));
canvas.drawColor(Color.TRANSPARENT);
mPaint.setStyle(Paint.Style.FILL);
mRectF.left = mCircleLineStrokeWidth / 2; // 左上角x
mRectF.top = mCircleLineStrokeWidth / 2; // 左上角y
mRectF.right = width - mCircleLineStrokeWidth / 2; // 左下角x
mRectF.bottom = height - mCircleLineStrokeWidth / 2; // 右下角y
//画内部实体圆
canvas.drawCircle(200, 200, 185, mPaint);
//画笔的空心设置
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(3);
//画中间比较细的空心圆
canvas.drawCircle(200, 200, 190, mPaint);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(10);
mPaint.setColor(Color.parseColor("#FE0407"));
//创建一个线程来控制最外层圆绘制的速度
new Thread(new Runnable() {
@Override
public void run() {
if (Sweep < mProgress) {
canvas.drawArc(mRectF, -90, ((float) Sweep / mMaxProgress) * 360, false, mPaint);
postInvalidate();
Sweep++;
}
}
}).start();
}
public void setMaxProgress(int maxProgress) {
this.mMaxProgress = maxProgress;
}
public void setProgress(int progress) {
this.mProgress = progress;
this.invalidate();
}
}
代码就是很简洁,至于如何画圆就不再说了,大家可以去看我的上一篇博客
《Android自定义View(一)(Paint和Canvas的基本使用)》
主要来说这个绘制的动画的实现流程,在上面我们定义了一个变量Sweep,这个属性就是指画最外层扇形扫过的角度,我们先建立一个线程,每次让扫过的角度+1(如果想让动画快一点,可以每次+5),这样每次绘制都会调用postInvalidate()函数来刷新绘制,看起来还算流畅,还不错。
二、自定义View在Activity中的使用
CircleProgressView mCircleProgressView = (CircleProgressView) findViewById(R.id.progressBar2);
mCircleProgressView.setProgress(70);
mCircleProgressView.setMaxProgress(100);
setProgress()中的参数就是你想传入的百分比参数,使用非常简单。
Demo我就不贴了,大家直接Copy这个类使用就ok,希望能帮到大家。