之前在做一个一android项目的时候遇到了一个需要自定义控件的需求还时圆形的进度条,最终如下图
核心代码
主要是,extends View 然后是在构造函数里面初始化一些基本的数据,还可以读取xml配置的值,在ondraw 函数里面得到画布的中心点,计算坐标,根据API 在进行绘制
public class RoundProgressBar extends View {
public RoundProgressBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
TypedArray mTypedArray = context.obtainStyledAttributes(attrs,
R.styleable.RoundProgressBar);
//获取自定义属性和默认值
roundColor = mTypedArray.getColor(R.styleable.RoundProgressBar_roundColor, Color.RED);
mTypedArray.recycle();
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//获取圆心的x坐标
int centreX = getWidth() / 2;
//获得圆心y坐标
int centreY = getHeight() / 2;
//圆环的半径
int radius = (int) (centreX - roundWidth);
paint.setStrokeWidth(roundWidth);
paint.setColor(Color.argb(255, 213, 1, 15)); //设置进度的颜色
RectF oval = new RectF(roundWidth, roundWidth, centreX + radius, centreY + radius);
paint.setStrokeWidth(roundWidth);
paint.setColor(Color.argb(255, 213, 1, 15)); //设置进度的颜色
RectF oval = new RectF(roundWidth, roundWidth, centreX + radius, centreY + radius);
switch (style) {
case STROKE: {
paint.setStyle(Paint.Style.STROKE);
canvas.drawArc(oval, 270, 360 * progress / max, false, paint); //根据进度画圆弧
break;
}
case FILL: {
paint.setStyle(Paint.Style.FILL_AND_STROKE);
if (progress != 0)
canvas.drawArc(oval, 270, 360 * progress / max, true, paint); //根据进度画圆弧
break;
}
}
}
源代码,在我的github 里面都会有的