圆形头像以及一些常见需求形状自定义ImageView组件

      在实际开发中,我们经常会遇到这样的需求,就是无论图片长啥样,我们都要其显示成圆形、圆形加一个边框、矩形加边框,带圆角的矩形等等,lib和demo下载地址:https://github.com/mapleyuan/RoundImageView。效果如下,大家有兴趣的可以下下来使用,发现有什么问题也欢迎向我提出。

 

下面我大概讲下实现。

首先当然是继承ImageView,重写onDraw()方法。我们来看看onDraw的实现:

    protected void onDraw(Canvas canvas) {

        canvas.save();

        drawPath();

        canvas.clipPath(mPath);

        super.onDraw(canvas); 

        canvas.restore();

        drawCanvas(canvas);

    }

先调用了一个绘制区域的方法,那再来看下这个方法的实现:

private void drawPath() {

……………………..……………………..

            省略不关键部分

……………………...…………………….

            case CIRCLE:

                float r = Math.min(width, height) / 2;

                mPath.reset();

                mPath.addCircle(width / 2, height / 2, r, Path.Direction.CW);

                mPath.close();

                break;

……………………...…………………….

            省略不关键部分

……………………...…………………….

        }

   可以看到,调用了addCircle方法,顺时针绘制了一个圆。回到onDraw方法,调用了Canvas的clipPath方法对view进行了裁剪,然后再绘制就相当于在上面盖了一层蒙板。OK,到这里,我们就已经实现了一个圆形头像。假如,你还不满足于此,比如想加上一个边框,那么

继续往下看,发现又调用了drawCanvas方法

private void drawCanvas(Canvas canvas) {

        int width = getWidth();

        int height = getHeight();

        if (mBorderWidth <= 0) {

            return;

        }

        mBorderPaint.setColor(mBorderColor);

        mBorderPaint.setStrokeWidth(mBorderWidth);

        mBorderPaint.setStyle(Paint.Style.STROKE);

        mBorderPaint.setAntiAlias(true);

……………………...…………………….

            省略不关键部分

……………………...…………………….

            case CIRCLE:

                float r = Math.min(width, height) / 2;

                canvas.drawCircle(width / 2, height / 2, r - mBorderWidth / 2, mBorderPaint);

                break;

……………………...…………………….

            省略不关键部分

……………………...…………………….

    }

     通过对画笔设置宽度,颜色,最后在canvas进行绘制圆圈。至此,我们基本上就实现了圆形imgeview功能,对于其他形状,原理类似。更多代码详情欢迎到https://github.com/mapleyuan/RoundImageView)上下载,也欢迎关注指出问题。后续也会陆续把平常常用组件放上去,欢迎关注下载,谢谢~

原文地址:https://www.cnblogs.com/mapleyuan/p/5204085.html