分享一个自定义view-圆形进度条,中间显示进度

分享一个自定义view-圆形进度条,中间显示进度_第1张图片

 

public class SportsView extends View {

    /*
        原理是画一大一小圆,小圆填充外部边距颜色,最中间画text
     */



    private int progress = 0;   //中间的进度数
    private int mCircleWidth = 20;   //圆环的宽度
    private int mCircleColor = Color.BLUE;     //圆环的默认颜色
    private int mTextColor = Color.BLACK;  //中间text的颜色
    private int mTextSize = 20; //中间text的size
    private Paint bigCirclePaint = new Paint();   //大圆的画笔
    private Paint smallCirclePaint = new Paint();   //小圆的画笔
    private Paint textPaint = new Paint(); //text的画笔
    private RectF mRectF = new RectF();


    public SportsView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public int getProgress(){
        return progress;
    }

    public void setProgress(int progress){
        this.progress = progress;
        invalidate();
    }


    public void setCircleColor(int color){
        this.mCircleColor = color;
        invalidate();
    }


    public void setCircleWidth(int circleWidth){
        this.mCircleWidth = circleWidth;
        invalidate();
    }


    @Override
    public void onDraw(Canvas canvas){
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();

        //设置大圆
        mRectF.set(0,0,width,height);      //设置大圆rect的长宽
        bigCirclePaint.setStyle(Paint.Style.STROKE);   //设置大圆为空心,不填充内部
        bigCirclePaint.setColor(mCircleColor);   //大圆颜色
        //画弧形,从0到给定进度的弧形,100对应360度,所以进度*3.6
        canvas.drawArc(mRectF,0, (float) (progress * 3.6),false,bigCirclePaint);

        //设置小圆
        mRectF.set(mCircleWidth,mCircleWidth,width - mCircleWidth,height - mCircleWidth);
        smallCirclePaint.setStyle(Paint.Style.STROKE); //小圆设置空心
        smallCirclePaint.setStrokeWidth(mCircleWidth * 2); //设置宽度,填充圆环颜色
        smallCirclePaint.setColor(mCircleColor); //设置小圆颜色
        //画弧,原理同上
        canvas.drawArc(mRectF,0,(float) (progress * 3.6),false,smallCirclePaint);

        //设置中间的文字
        textPaint.setColor(mTextColor);
        textPaint.setStrokeWidth(200);
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setTextSize(dpToPixel(mTextSize));
        textPaint.setTextAlign(Paint.Align.CENTER);//设置对齐方式
        canvas.drawText(progress + "%",width / 2,(height - textPaint.ascent() - textPaint.descent()) / 2,textPaint);
    }



    private float dpToPixel(float dp){
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        return dp * metrics.density;
    }

}

 

你可能感兴趣的:(android,studio)