自己写一个 RoundImageView

作者: 彼岸sakura | 来源:发表于2017-07-20 18:03 被阅读125次

    自定义控件 几乎是 Android 开发者进阶必修课,然而因为过程比较考验基本功(源码解读和数学知识),不少朋友会感觉比较苦恼,尤其像笔者这样半路出家的。踩过一些坑后,笔者总结的经验如下——

    • 对理论知识,要着眼大局,把目标定为弄清它整体的运转流程,而不是拘泥于某个细节的实现内容。因为很多系统性的知识(比如控件的绘制全程),都不是一个人总结出来的,非要把每一行代码都弄清楚,结果就像是盲人摸象,永远也摸不透。
    • 对具体实践,要抽丝剥茧,把目标定为弄清它每一步做了什么事,而不是简单把实现死记硬背下来。因为自定义控件千变万化,单纯去记某一个的实现内容,结果就像是猴子掰苞谷,学啥忘啥。

    以上两点,其实也适用于信息时代很多新知识的学习。
    下面我们来实现一个 自定义控件,需求如下:

    • 圆形控件,能将图片内切成一张圆图,然后展示出来
    • 能在 xml 文件里设定有无边框,边框有多宽,是什么颜色

    定义所需属性

    打开死丢丢,新建一个项目 RoundImageViewTest,然后在 res/values/ 目录下新建一个配置文件 attrs.xml

    1.jpeg
    然后在里面定义我们要写的 自定义控件 的配置属性——
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="RoundImageView">
            <attr name="border_width" format="dimension" />
            <attr name="border_color" format="color" />
        </declare-styleable>
    </resources>
    

    首先我们想要的是一个图片控件,因此可以直接继承 ImageView 或者它的子类,这样可以少写很多实现过程,只须考虑 切图边框 两点。切图是在代码里面做的,于是要定义的,只剩下边框相关的内容了。
    边框的 宽度 如果设成 0,就相当于没有,所以只定义 宽度颜色 2 个属性即可,border_widthborder_color
    至于format,它的取值不少,除了图示的 dimensioncolor,常用的还有 stringintegerboolean。具体怎么取?温故知新一番吧。

        <!-- 从上到下 6 个属性的 format 分别是 dimension,dimension,color,
    string,integer 和 boolean。-->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/colorPrimary"
            android:text="Hello world!"
            android:lines="3"
            android:clickable="false"/>
    

    配置写好了,下一步就是自定义 View 类了。

    获取已定义的属性

    新建一个类 RoundImageView,继承 AppCompatImageView

    public class RoundImageView extends AppCompatImageView {
        private Context mContext;//上下文
        private int mBorderWidth;//边框宽度
        private int mBorderColor;//边框颜色
        private int mDefaultWidth = 0;//默认边框为0,也就是没有边框
        private int mDefaultColor = 0xffffffff;//默认颜色为纯白
    
        public RoundImageView(Context context) {
            this(context, null);//在代码里new实例时,会调用这个构造器
        }
        public RoundImageView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);//在xml里配置view时,会调用这个构造器
        }
        public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            mContext = context;
            setAttributes(attrs);
        }
        //从配置文件中获取属性值
        private void setAttributes(AttributeSet attrs) {
            TypedArray ta = mContext.obtainStyledAttributes(attrs, 
                    R.styleable.RoundImageView);
            mBorderWidth = ta.getDimensionPixelSize(
                    R.styleable.RoundImageView_border_width, mDefaultWidth);
            mBorderColor = ta.getColor(
                    R.styleable.RoundImageView_border_color, mDefaultColor);
            ta.recycle();//赋值完后记得回收
        }
    }
    

    构造器一般 重写前三个,让前两个都指向第三个。在第三个构造器里,获取我们之前在配置文件里定义的属性即可。
    下一步就是重写onMeasure()onDraw(),完成 测量绘制 了。不过某些时候onMeasure()并不是必须的——你问什么时候?

    • 系统会在onMeasure()里面帮我们测量控件的宽高。
    • 当你给宽高设定了具体的值,测量出来的就是那个值。
    • 当你给宽高设定的是类似MATCH_PARENT或者WRAP_CONTENT,测量出来的默认是MATCH_PARENT
    • 因此,当我们需要让自定义控件能够自适应内容宽高时,就要重写onMeasure;如果没有这个需求,可以不重写。

    考虑到圆形图片一般被用来显示 头像 或者 缩略图,而这些在实际开发中往往都是指定大小的,此处我们就不重写onMeasure ()了,直接开始onDraw()

    重写绘制流程

    记得去掉父类的绘制流程。
    因为我们最终绘上去的图要和控件 内切,所以增加两个成员变量mWidthmHeight,用于记录控件的宽和高,方便后面的计算。

        private int mWidth;//自定义view的宽度
        private int mHeight;//自定义view的高度
        @Override
        protected void onDraw(Canvas canvas) {
            //super.onDraw(canvas);
            if (getWidth() == 0 || getHeight() == 0) {
                return;
            }
            if (mWidth == 0) {
                mWidth = getWidth();
            }
            if (mHeight == 0) {
                mHeight = getHeight();
            }
        }
    

    下一步做什么呢?不少新手都容易摸不清头脑,包括笔者。
    这个时候最好的方法是开个记事本写 伪码,相当于学生时代写作文打提纲。

    if (有边框) {
        画边框();
    } else {
    
    }
    画圆图();
    

    有无边框很好判断,宽度 0 就是没有。
    边框也很好画,就是一个圆,只是注意要画在控件 居中 的位置。
    圆图稍微难办一点,首先我们要把图片资源拿到,并且和控件的宽高进行 适配;其次要裁剪它,最好是按资源的 内切圆 裁剪,可以显示尽量多的内容;最后同样把它画在控件 居中 的位置。
    这么一来又分两种情况——
    资源是 正方形:这个好办,直接按内切圆裁剪。
    资源是 矩形:需要先将其居中裁剪成一个正方形,然后再按内切圆裁剪。不对,矩形有两种!还得再分出「宽 > 高」和「高 > 宽」两种情况。
    因此我们「画圆图」方法的伪码应该是——

    画圆图() {
        if (宽 > 高) {
            居中裁剪边长 = 高的正方形();
        } else if (高 > 宽) {
            居中裁剪边长 = 宽的正方形();
        } else {
    
        }
        裁剪正方形的内切圆();
    }
    

    矩形变正方形很好办,Bitmap.createBitmap(矩形图, 横坐标, 纵坐标, 边长, 边长)即可;正方形变圆形的话,需要用到 图像混合 知识。
    这里你暂时只需要知道这么做——

    • 先画一个圆。
    • 然后调用paint.setXferMode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN))
    • 再画你图像,这样最终显示的就是「图像与这个圆相交的部分」。

    图像混合 的其它知识有兴趣的朋友,推荐看这篇文——

    目标明确了,我们的代码就好写了,直接上——

        @Override
        protected void onDraw(Canvas canvas) {
            //获取控件的宽与高
            if (getWidth() == 0 || getHeight() == 0) {
                return;
            }
            if (mWidth == 0) {
                mWidth = getWidth();
            }
            if (mHeight == 0) {
                mHeight = getHeight();
            }
            //根据是否有边框,进行处理
            int radius;
            boolean b = mWidth < mHeight;
            if (mBorderWidth == 0) {//没有边框时,半径为宽高较小值的一半
                radius = b ? mWidth / 2 : mHeight / 2;
            } else {//有边框时,半径为宽高较小值的一半,减去边框宽度
                radius = b ? mWidth / 2 - mBorderWidth : mHeight / 2 - mBorderWidth;
                //然后先绘制边框
                drawBorder(canvas, radius, mBorderColor);
            }
            //获取资源图片,裁剪成圆形
            Drawable drawable = getDrawable();
            if (drawable == null) {
                return;
            }
            Bitmap resource = ((BitmapDrawable) drawable).getBitmap();
            if (resource == null) {
                return;
            }
            Bitmap result = getRoundBitmap(
                    resource.copy(Bitmap.Config.ARGB_8888, true), radius);
            //绘制到view的正中央
            canvas.drawBitmap(result, mWidth / 2 - radius, mHeight / 2 - radius, null);
        }
        //获取裁剪后的圆形图片
        public Bitmap getRoundBitmap(Bitmap bmp, int radius) {
            Bitmap squareBmp, scaledBmp;//正方形图,适配后的正方形图
            int x, y, squareSize;//横坐标,纵坐标,正方形边长
            //将原图片裁剪成正方形,边长为长与宽的较小值
            int bmpWidth = bmp.getWidth();
            int bmpHeight = bmp.getHeight();
            if (bmpWidth > bmpHeight) {
                squareSize = bmpHeight;
                x = (bmpWidth - bmpHeight) / 2;
                y = 0;
                squareBmp = Bitmap.createBitmap(bmp, x, y, squareSize, squareSize);
            } else if (bmpHeight > bmpWidth) {
                squareSize = bmpWidth;
                x = 0;
                y = (bmpHeight - bmpWidth) / 2;
                squareBmp = Bitmap.createBitmap(bmp, x, y, squareSize, squareSize);
            } else {
                squareBmp = bmp;
            }
            //将正方形图片与view的半径适配
            int diameter = radius * 2;
            if (squareBmp.getWidth() != diameter || squareBmp.getHeight() != diameter) {
                scaledBmp = Bitmap.createScaledBitmap(
                        squareBmp, diameter, diameter, true);
            } else {
                scaledBmp = squareBmp;
            }
            //绘制圆环
            Bitmap result = Bitmap.createBitmap(
                    scaledBmp.getWidth(), scaledBmp.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(result);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setFilterBitmap(true);
            paint.setDither(true);
            canvas.drawCircle(scaledBmp.getWidth() / 2, scaledBmp.getHeight() / 2,
                    radius, paint);
            //绘制混合图像,这样最终显示的就是图像与圆环相交的部分,即圆形图片
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            Rect rect = new Rect(0, 0, scaledBmp.getWidth(), scaledBmp.getHeight());
            canvas.drawBitmap(scaledBmp, rect, rect, paint);
            //记得回收
            bmp.recycle();
            squareBmp.recycle();
            scaledBmp.recycle();
            return result;
        }
        //绘制边框
        private void drawBorder(Canvas canvas, int radius, int color) {
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setFilterBitmap(true);
            paint.setDither(true);
            paint.setColor(color);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(mBorderWidth);
            canvas.drawCircle(mWidth / 2, mHeight / 2, radius, paint);
        }
    

    大功告成!可以测试了。

    布局文件

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:tools="http://schemas.android.com/tools"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:background="#cccccc"
        android:padding="16dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.jin.roundimageviewtest.MainActivity">
        <com.example.jin.roundimageviewtest.RoundImageView
            android:src="@mipmap/test"
            android:layout_width="100dp"
            android:layout_height="100dp" />
        <com.example.jin.roundimageviewtest.RoundImageView
            android:src="@mipmap/test"
            android:layout_marginTop="16dp"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:border_width="8dp"/>
        <com.example.jin.roundimageviewtest.RoundImageView
            android:src="@mipmap/test"
            android:layout_marginTop="16dp"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:border_width="8dp"
            app:border_color="@color/colorAccent"/>
    </LinearLayout>
    

    展示效果

    preview.png
    本文结束,欢迎拍砖指教。
    文章代码下载

    相关文章

      网友评论

        本文标题:自己写一个 RoundImageView

        本文链接:https://www.haomeiwen.com/subject/ntbdkxtx.html