安卓自定义View之画图

安卓自定义view画图简单实现:

1.首先需要在values目录下新建一个attrs.xml文件,可以定义所需要定义View的各种属性

文件里的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CircleView">
        <attr name="circleColor" format="color"></attr>
        <attr name="circleRadius" format="dimension"></attr>
        <attr name="circleTest" format="string"></attr>
    </declare-styleable>
</resources>


然后自定义一个类继承View重写前两个构造器:

public class CircleView extends View {

    private Paint paint;
    private int color;
    private float dimension;

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

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

    private void init(Context context, AttributeSet attrs) {
//得到typedarray对象,使用它定义各种属性
 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
        color = typedArray.getColor(R.styleable.CircleView_circleColor, Color.BLUE);
        dimension = typedArray.getDimension(R.styleable.CircleView_circleRadius, 50);
        typedArray.getString(R.styleable.CircleView_circleTest);
        typedArray.recycle();

        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(color);
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(200,200,dimension,paint);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值