自定义->画一个圆

最简单的自定义View,画一个圆。
自定义的意义:现有的不能满足需求,所以我们自己来实现我们的需求。

  1. 自定义圆需要设定一些属性,如圆的颜色,圆的的宽度。在Value下面新建一个attrs的xml文件,
    name后面跟的上是我们自定义的属性标签 format是告诉系统这个标签是来做什么的
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="Circle">
        <attr name="circle_Color" format="color"></attr>
        <attr name="cirlce_Width" format="dimension"></attr>
    </declare-styleable>

</resources>
  1. 继承一个View,实现其构造方法,在构造方法里获得自定义属性值
public CirlcleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        //1.获得自定义属性值的一个容器
        TypedArray mTd = context.obtainStyledAttributes(attrs, R.styleable.Circle);
        //2.通过属性容器获得属性,如果没有就使用默认值
        roundColor = mTd.getColor(R.styleable.Circle_circle_Color, Color.GREEN);
        roundWidth = mTd.getDimension(R.styleable.Circle_cirlce_Width, 5);
        //3.释放重复利用
        mTd.recycle();
    }

3.在onDraw方法里进行圆的绘制

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        /*
         * 画一个圆
         * 1. 需要有圆心坐标
         * 2. 需要有半径
         */
        int center = getWidth()/2;  //圆心x坐标
        int radius = (int) (center-roundWidth/2);   //圆环的半径
        //设置圆的各项属性
        paint.setColor(roundColor);
        paint.setStyle(Paint.Style.STROKE);     //空心
        paint.setStrokeWidth(roundWidth);       //圆环的宽度
        paint.setAntiAlias(true);       //抗锯齿

        canvas.drawCircle(center, center, radius, paint);   //绘制圆
    }

4.在xml里进行使用,这里一定要引入自定义的属性,在最顶层布局里面加入 xmlns:app=”http://schemas.android.com/apk/res-auto”就可以了,红色部分是自己可以写的,意思就是通过app这个标签,可以找到我们要使用的属性空间

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <com.example.circle.CirlcleView
        android:id="@+id/circle"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        app:circle_Color="#000000"
        app:cirlce_Width="10dp" />

</RelativeLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值