欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android 自定义View画圆环统计图

程序员文章站 2022-05-30 20:06:53
...
public class MyView extends View {

    public MyView(Context context) {
        super(context);
    }

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

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setData() {
        //设置数据
        invalidate();//用它来刷新view,显示设置数据后的图
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 获取控件的高度和宽度
        int width = getWidth();
        int height = getHeight();
        
        Log.e("MyView", "width:" + width);
        Log.e("MyView", "height:" + height);

        Paint paint_bg = new Paint();
        paint_bg.setStrokeWidth(100);
        paint_bg.setStyle(Paint.Style.FILL);
        paint_bg.setColor(Color.parseColor("#FF0000"));

        int banjing_bg;
        if (width > height) {
            banjing_bg = height / 2 - 100;
        } else {
            banjing_bg = width / 2 - 100;
        }
        Log.e("MyView", "banjing:" + banjing_bg);
        RectF oval = new RectF(width / 2 - banjing_bg, height / 2 - banjing_bg, width / 2 + banjing_bg, height / 2 + banjing_bg);
        canvas.drawArc(oval, 0, 270, true, paint_bg);


        Paint paint = new Paint();
        paint.setStrokeWidth(100);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.parseColor("#FFFFFF"));
        int banjing;
        if (width > height) {
            banjing = height / 2 - 200;
        } else {
            banjing = width / 2 - 200;
        }
        Log.e("MyView", "banjing:" + banjing);
        RectF oval1 = new RectF(width / 2 - banjing, height / 2 - banjing, width / 2 + banjing, height / 2 + banjing);
        canvas.drawArc(oval1, 0, 360, true, paint);

    }

}

刚开始宽高一直设置不对,后来画了个图,算了一下到底应该是多少,才弄对,看来数学还是很有用的。

效果图:

 

Android 自定义View画圆环统计图

 

原图是没有变形的,一个正圆的圆环,不知道上传之后会变成什么样子。

相关标签: 自定义View