233_自定义一个百分比占比沙漏型的圆

来源:互联网 发布:java后端工程师 编辑:程序博客网 时间:2024/05/29 19:39






自定义一个百分比占比沙漏型的圆


很简单的一个东西


就是一个圆,然后一个水平线,
水平线下面的部分就是所占的百分比






直接上代码




public class PercentCircleView extends View {


    private double percent = 0;


    public PercentCircleView(Context context, double percent) {
        this(context);
        this.percent = percent;
    }


    public PercentCircleView(Context context) {
        this(context, null);
    }


    public PercentCircleView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public PercentCircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


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


        //整个圆的颜色
        int fillColor = getResources().getColor(R.color.color_single_FDF7E8);


        //占比的半圆的颜色
        int percentColor = getResources().getColor(R.color.color_single_EEBD2B);


        //获取高和宽
        int width = getWidth();
        int height = getHeight();


        //生成一个新的层
        int save = canvas.saveLayer(0, 0, width, height, null, Canvas.ALL_SAVE_FLAG);


        //创建画笔
        Paint fill = new Paint(Paint.ANTI_ALIAS_FLAG);


        //设置模式
        fill.setStyle(Paint.Style.FILL);


        //设置颜色
        fill.setColor(fillColor);


        //画圆
        canvas.drawOval(new RectF(0, 0, width, height), fill);


        //设置颜色
        fill.setColor(percentColor);


        //设置xfetmode模式
        fill.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));


        //画矩形
        canvas.drawRect(0, (float) ((1 - percent) * height), width, height, fill);


        //缓冲到画布上面去
        canvas.restoreToCount(save);
    }











0 0