Android利用canvas制作环形进度条

使用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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值