Android 实现一个简单的自定义View

自定义View的相关文章:

我们实现这样一个自定义View,绘制一个圆,半径和颜色可以通过属性设置。

public class MyView extends View {
    /**
     * 圆的半径,默认画出最大圆
     */
    private float radius;
    /**
     * 圆的颜色
     */
    private int color;

    private Paint mPaint;

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

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

        //获取设置的属性值
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        radius = typedArray.getDimension(R.styleable.MyView_radius, 0);
        color = typedArray.getColor(R.styleable.MyView_android_color, Color.RED);
        typedArray.recycle();
        //初始化Paint
        mPaint = new Paint();
        mPaint.setColor(color);
    }

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

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //计算半径,如果属性中设置了半径则使用设置的值,否则是宽和高一半的较小值
        float mRadius = radius == 0 ? Math.min(getWidth() / 2, getHeight() / 2) : radius;
        //绘制圆
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, mRadius, mPaint);
    }
}

在res/values目录下创建attrs.xml,这里面我们定义了我们需要的属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="radius" format="dimension"></attr>
        <attr name="android:color"/>
    </declare-styleable>
</resources>

使用:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="qiwei.com.frameworknote.ui.MainActivity">

    <qiwei.com.frameworknote.ui.MyView
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:radius="20dp"
        android:color="@color/colorPrimaryDark"/>

</android.support.constraint.ConstraintLayout>

这里写图片描述

所以自定义View实现的步骤:

  1. 创建View并继承View
  2. 设置View属性
  3. 获取View属性值
  4. 初始化Paint(Paint用于绘制)
  5. 重写onMesure方法,不是必须的,此View未写,后面会详细介绍
  6. 重写onDraw方法

    自定义View重点在onDraw方法,这个方法里面我们要绘制出界面下一篇文章我们会详细的介绍各个步骤。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老孟Flutter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值