您的位置:首页 > 移动开发 > Android开发

Android利用canvas制作环形进度条

2015-12-23 18:28 701 查看
使用canvas画出如下图所示的动态图



这里下面为实现的代码!

public class MyView extends View {
private Paint paint;
private int roundProgressColor;//设置圆环的颜色
private float roundWidth;//圆环的宽度
private int process = 1;
private RectF oval;
private SweepGradient mshape;
public MyView(Context context) {
this(context, null);
}
public MyView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint();
TypedArray mtypeArray = context.obtainStyledAttributes(attrs, R.styleable.RoundProgressBar);
roundWidth = mtypeArray.getDimension(R.styleable.RoundProgressBar_roundWidth, 30);
roundProgressColor = mtypeArray.getColor(R.styleable.RoundProgressBar_roundProgressColor, Color.GREEN);
mtypeArray.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int center = getWidth() / 2;//获取圆心
int radius = (int) (center - roundWidth / 2);
paint.setStrokeWidth(roundWidth);
paint.setColor(roundProgressColor);
oval = new RectF(center - radius, center - radius, center + radius, center + radius);
paint.setStyle(Paint.Style.STROKE);
PathEffect effects = new DashPathEffect(new float[]{10, 10, 10, 10}, 1);//设置虚线
paint.setAntiAlias(true);
paint.setPathEffect(effects);
mshape = new SweepGradient(center, center + radius, new int[]{Color.GREEN, Color.RED}, null);//设置颜色为渐变
paint.setShader(mshape);
canvas.drawArc(oval, 120, process % 300, false, paint);
invalidate();//刷新view
process++;
}
}

在values中建一个attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundProgressBar">
<attr name="roundColor" format="color" />
<attr name="roundProgressColor" format="color" />
<attr name="roundWidth" format="dimension"></attr>
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
<attr name="max" format="integer"></attr>
<attr name="textIsDisplayable" format="boolean"></attr>
<attr name="style">
<enum name="STROKE" value="0"></enum>
<enum name="FILL" value="1"></enum>
</attr>
</declare-styleable>
</resources>
 

参考的文章有:

http://blog.csdn.net/q12q1ty/article/details/50350205

http://blog.csdn.net/xiaanming/article/details/10298163

http://blog.csdn.net/t12x3456/article/details/10473225

Android技术交流群:284128443
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息