Android 自定义View控件画圆

时间:2024-05-18 22:39:23

今天自定义view画圆,使用到的就是Android也给我们提供了这两样东西:Paint和Canvas,由于在代码中都有对使用方法的介绍 我也不多说,来看自定义View的代码:


首先创建一个类来继承View并且实现它的两个方法:

class ShapeView extends View {
    private final  Paint paint;
    private final Context context;

    public ShapeView(Context context) {

        // TODO Auto-generated constructor stub
        this(context, null);
    }

    public ShapeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        this.context = context;
        this.paint = new Paint();
        this.paint.setAntiAlias(true); //消除锯齿
        this.paint.setStyle(Paint.Style.FILL); //绘制空心圆
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        int center = getWidth()/2;
        int innerCircle = dip2px(context, 83); //设置内圆半径
        int ringWidth = dip2px(context, 5); //设置圆环宽度

        //绘制内圆
        this.paint.setARGB(155, 167, 190, 206);
        this.paint.setStrokeWidth(2);
        canvas.drawCircle(center,center, innerCircle, this.paint);

        //绘制圆环
        this.paint.setARGB(255, 212 ,225, 233);
        this.paint.setStrokeWidth(ringWidth);
        canvas.drawCircle(center,center, innerCircle+1+ringWidth/2, this.paint);

        //绘制外圆
        this.paint.setARGB(155, 167, 190, 206);
        this.paint.setStrokeWidth(2);
        canvas.drawCircle(center,center, innerCircle+ringWidth, this.paint);


        super.onDraw(canvas);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

}
布局文件中引用这个类:

<zhangpeisen.bawei.com.test0627.ShapeView
    android:id="@+id/shape"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
这样就能看到一个运行的圆了。

效果如图:

Android 自定义View控件画圆