【Android自定义View实战】之自定义圆形头像CircleImageView支持加载网络图片

转载请注明出处:http://blog.csdn.net/linglongxin24/article/details/52923384 【DylanAndroid的csdn博客】


在Android开发中我们常常用到圆形的头像,如果每次加载之后再进行圆形裁剪特别麻烦。所以在这里写一个自定义圆形ImageView,直接去加载网络图片,这样的话就特别的方便。

先上效果图

这里写图片描述

主要的方法

1.让自定义 CircleImageView 继承ImageView

/**
 * 自定义圆形头像
 * Created by Dylan on 2015/11/26 0026.
 */
public class CircleImageView extends ImageView {
}

2.在构造方法中获取在xml中设置的值


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

    public CircleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        super.setScaleType(SCALE_TYPE);
        /**
         * 获取在xml中声明的属性
         */
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);//获取xml中的属性

        mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
        mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR);

        a.recycle();

        mReady = true;

        if (mSetupPending) {
            setup();
            mSetupPending = false;
        }
    }

3.初始化各种参数设置


    /**
     * 画圆形图的初始化工作
     */
    private void setup() {
        if (!mReady) {
            mSetupPending = true;
            return;
        }

        if (mBitmap == null) {
            return;
        }
        /**
         *调用这个方法来产生一个画有一个位图的渲染器(Shader)。
         bitmap   在渲染器内使用的位图
         tileX      The tiling mode for x to draw the bitmap in.   在位图上X方向花砖模式
         tileY     The tiling mode for y to draw the bitmap in.    在位图上Y方向花砖模式
         TileMode:(一共有三种)
         CLAMP  :如果渲染器超出原始边界范围,会复制范围内边缘染色。
         REPEAT :横向和纵向的重复渲染器图片,平铺。
         MIRROR :横向和纵向的重复渲染器图片,这个和REPEAT 重复方式不一样,他是以镜像方式平铺。
         */
        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        /**
         * 设置画圆形的画笔
         */
        mBitmapPaint.setAntiAlias(true);//设置抗锯齿
        mBitmapPaint.setShader(mBitmapShader);//绘制图形时的图形变换

        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setAntiAlias(true);
        mBorderPaint.setColor(mBorderColor);
        mBorderPaint.setStrokeWidth(mBorderWidth);

        mBitmapHeight = mBitmap.getHeight();
        mBitmapWidth = mBitmap.getWidth();
        /**
         * 设置边框矩形的坐标
         */
        mBorderRect.set(0, 0, getWidth(), getHeight());
        /**
         * 设置边框圆形的半径为图片的宽度和高度的一半的最大值
         */
        mBorderRadius = Math.max((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
        /**
         * 设置图片矩形的坐标
         */
        mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
        /**
         * 设置图片圆形的半径为图片的宽度和高度的一半的最大值
         */
        mDrawableRadius = Math.max(mDrawableRect.height() / 2, mDrawableRect.width() / 2);

        updateShaderMatrix();
        /**
         * 调用onDraw()方法进行绘画
         */
        invalidate();
    }
 /**
     * 更新位图渲染
     */
    private void updateShaderMatrix() {
        float scale;
        float dx = 0;
        float dy = 0;
        /**
         * 重置
         */
        mShaderMatrix.set(null);
        /**
         *计算缩放比,因为如果图片的尺寸超过屏幕,那么就会自动匹配到屏幕的尺寸去显示。
         * 确定移动的xy坐标
         *
         */
        if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
            scale = mDrawableRect.width() / (float) mBitmapWidth;
            dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
        } else {
            scale = mDrawableRect.height() / (float) mBitmapHeight;
            dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
        }

        mShaderMatrix.setScale(scale, scale);
        mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth);
        /**
         * 设置shader的本地矩阵
         */
        mBitmapShader.setLocalMatrix(mShaderMatrix);
    }

4.画圆

 @Override
    protected void onDraw(Canvas canvas) {
        if (getDrawable() == null) {
            return;
        }
        /**
         * 画圆形图片
         */
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
        /**
         * 画圆形边框
         */
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
    }

完整代码,有完整的注释

1.CircleImageView 主类


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.kejiang.yuandl.R;
import com.kejiang.yuandl.utils.ImageSizeUtil;


/**
 * 自定义圆形头像
 * Created by Dylan on 2015/11/26 0026.
 */
public class CircleImageView extends ImageView {
    /**
     * 圆形头像默认,CENTER_CROP!=系统默认的CENTER_CROP;
     * 将图片等比例缩放,让图像的长边边与ImageView的边长度相同,短边不够的留空白,缩放后截取圆形部分进行显示。
     */
    private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;
    /**
     * 图片的压缩质量
     * ALPHA_8就是Alpha由8位组成,------ALPHA_8 代表8位Alpha位图
     * ARGB_4444就是由4个4位组成即16位,------ARGB_4444 代表16位ARGB位图
     * ARGB_8888就是由4个8位组成即32位,------ARGB_8888 代表32位ARGB位图
     * RGB_565就是R为5位,G为6位,B为5位共16位,------ARGB_565 代表8位RGB位图
     */
    private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
    /**
     * 默认ColorDrawable的宽和高
     */
    private static final int COLORDRAWABLE_DIMENSION = 1;
    /**
     * 默认边框宽度
     */
    private static final int DEFAULT_BORDER_WIDTH = 0;
    /**
     * 默认边框颜色
     */
    private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
    /**
     * 画图片的矩形
     */
    private final RectF mDrawableRect = new RectF();
    /**
     * 画边框的矩形
     */
    private final RectF mBorderRect = new RectF();
    /**
     * 对图片进行缩放和移动的矩阵
     */
    private final Matrix mShaderMatrix = new Matrix();
    /**
     * 画图片的画笔
     */
    private final Paint mBitmapPaint = new Paint();
    /**
     * 画边框的画笔
     */
    private final Paint mBorderPaint = new Paint();
    /**
     * 默认边框颜色
     */
    private int mBorderColor = DEFAULT_BORDER_COLOR;
    /**
     * 默认边框宽度
     */
    private int mBorderWidth = DEFAULT_BORDER_WIDTH;

    private Bitmap mBitmap;
    /**
     * 产生一个画有一个位图的渲染器(Shader)
     */
    private BitmapShader mBitmapShader;
    /**
     * 图片的实际宽度
     */
    private int mBitmapWidth;
    /**
     * 图片实际高度
     */
    private int mBitmapHeight;
    /**
     * 图片半径
     */
    private float mDrawableRadius;
    /**
     * 边框半径
     */
    private float mBorderRadius;
    /**
     * 是否初始化准备好
     */
    private boolean mReady;
    /**
     * 内边距
     */
    private boolean mSetupPending;

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

    public CircleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        super.setScaleType(SCALE_TYPE);
        /**
         * 获取在xml中声明的属性
         */
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);//获取xml中的属性

        mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
        mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR);

        a.recycle();

        mReady = true;

        if (mSetupPending) {
            setup();
            mSetupPending = false;
        }
    }

    @Override
    public ScaleType getScaleType() {
        return SCALE_TYPE;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getDrawable() == null) {
            return;
        }
        /**
         * 画圆形图片
         */
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
        /**
         * 画圆形边框
         */
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        setup();
    }

    /**
     * 获取边框颜色
     *
     * @return
     */
    public int getBorderColor() {
        return mBorderColor;
    }

    /**
     * 设置边框颜色
     *
     * @param borderColor
     */
    public void setBorderColor(int borderColor) {
        if (borderColor == mBorderColor) {
            return;
        }

        mBorderColor = borderColor;
        mBorderPaint.setColor(mBorderColor);
        invalidate();
    }

    /**
     * 获取边框宽度
     *
     * @return
     */
    public int getBorderWidth() {
        return mBorderWidth;
    }

    /**
     * 设置边框宽度
     *
     * @param borderWidth
     */
    public void setBorderWidth(int borderWidth) {
        if (borderWidth == mBorderWidth) {
            return;
        }

        mBorderWidth = borderWidth;
        setup();
    }

    /**
     * 设置资源图片
     *
     * @param bm
     */
    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        mBitmap = bm;
        setup();
    }

    /**
     * 设置资源图片
     *
     * @param drawable
     */
    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        mBitmap = getBitmapFromDrawable(drawable);
        setup();
    }

    /**
     * 设置资源id
     *
     * @param resId
     */
    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        mBitmap = getBitmapFromDrawable(getDrawable());
        setup();
    }

    /**
     * 获取资源图片
     *
     * @param drawable
     * @return
     */
    private Bitmap getBitmapFromDrawable(Drawable drawable) {
        if (drawable == null) {
            return null;
        }

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        try {
            Bitmap bitmap;

            if (drawable instanceof ColorDrawable) {
                bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
            } else {
                ImageSizeUtil.ImageSize imageSize = ImageSizeUtil.getImageViewSize(this);
                bitmap = Bitmap.createBitmap(imageSize.width,
                        imageSize.height, BITMAP_CONFIG);
            }

            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

    /**
     * 画圆形图的方法
     */
    private void setup() {
        if (!mReady) {
            mSetupPending = true;
            return;
        }

        if (mBitmap == null) {
            return;
        }
        /**
         *调用这个方法来产生一个画有一个位图的渲染器(Shader)。
         bitmap   在渲染器内使用的位图
         tileX      The tiling mode for x to draw the bitmap in.   在位图上X方向花砖模式
         tileY     The tiling mode for y to draw the bitmap in.    在位图上Y方向花砖模式
         TileMode:(一共有三种)
         CLAMP  :如果渲染器超出原始边界范围,会复制范围内边缘染色。
         REPEAT :横向和纵向的重复渲染器图片,平铺。
         MIRROR :横向和纵向的重复渲染器图片,这个和REPEAT 重复方式不一样,他是以镜像方式平铺。
         */
        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        /**
         * 设置画圆形的画笔
         */
        mBitmapPaint.setAntiAlias(true);//设置抗锯齿
        mBitmapPaint.setShader(mBitmapShader);//绘制图形时的图形变换

        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setAntiAlias(true);
        mBorderPaint.setColor(mBorderColor);
        mBorderPaint.setStrokeWidth(mBorderWidth);

        mBitmapHeight = mBitmap.getHeight();
        mBitmapWidth = mBitmap.getWidth();
        /**
         * 设置边框矩形的坐标
         */
        mBorderRect.set(0, 0, getWidth(), getHeight());
        /**
         * 设置边框圆形的半径为图片的宽度和高度的一半的最大值
         */
        mBorderRadius = Math.max((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
        /**
         * 设置图片矩形的坐标
         */
        mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
        /**
         * 设置图片圆形的半径为图片的宽度和高度的一半的最大值
         */
        mDrawableRadius = Math.max(mDrawableRect.height() / 2, mDrawableRect.width() / 2);

        updateShaderMatrix();
        /**
         * 调用onDraw()方法进行绘画
         */
        invalidate();
    }

    /**
     * 更新位图渲染
     */
    private void updateShaderMatrix() {
        float scale;
        float dx = 0;
        float dy = 0;
        /**
         * 重置
         */
        mShaderMatrix.set(null);
        /**
         *计算缩放比,因为如果图片的尺寸超过屏幕,那么就会自动匹配到屏幕的尺寸去显示。
         * 确定移动的xy坐标
         *
         */
        if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
            scale = mDrawableRect.width() / (float) mBitmapWidth;
            dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
        } else {
            scale = mDrawableRect.height() / (float) mBitmapHeight;
            dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
        }

        mShaderMatrix.setScale(scale, scale);
        mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth);
        /**
         * 设置shader的本地矩阵
         */
        mBitmapShader.setLocalMatrix(mShaderMatrix);
    }

}

2.里面所使用到的ImageSizeUtil

public class ImageSizeUtil
{
    /**
     * 根据ImageView获适当的压缩的宽和高
     * 
     * @param imageView
     * @return
     */
    public static ImageSize getImageViewSize(ImageView imageView)
    {

        ImageSize imageSize = new ImageSize();
        DisplayMetrics displayMetrics = imageView.getContext().getResources()
                .getDisplayMetrics();
        

        LayoutParams lp = imageView.getLayoutParams();

        int width = imageView.getWidth();// 获取imageview的实际宽度
        if (width <= 0)
        {if(lp!=null){
            width = lp.width;// 获取imageview在layout中声明的宽度
        }

        }
        if (width <= 0)
        {
             //width = imageView.getMaxWidth();// 检查最大值
            width = getImageViewFieldValue(imageView, "mMaxWidth");
        }
        if (width <= 0)
        {
            width = displayMetrics.widthPixels;
        }

        int height = imageView.getHeight();// 获取imageview的实际高度
        if (height <= 0)
        {if(lp!=null){
            height = lp.height;// 获取imageview在layout中声明的宽度
        }

        }
        if (height <= 0)
        {
            height = getImageViewFieldValue(imageView, "mMaxHeight");// 检查最大值
        }
        if (height <= 0)
        {
            height = displayMetrics.heightPixels;
        }
        imageSize.width = width;
        imageSize.height = height;

        return imageSize;
    }

    public static class ImageSize
    {
        public int width;
        public  int height;
    }
}

用法

布局文件


    <com.bulemobi.yuandl.view.CircleImageView
        android:id="@+id/ci"
        android:layout_width="180dp"
        android:layout_height="180dp"
        android:scaleType="centerCrop"
        android:layout_gravity="center_horizontal"
        app:border_width="1dp"
        app:border_color="#FF0000"
        />

Activity中的代码,用xutils3加载图片

  CircleImageView circleImageView= (CircleImageView) findViewById(R.id.ci);
        x.image().bind(circleImageView,url,new ImageOptions.Builder().setImageScaleType(ImageView.ScaleType.CENTER_CROP).build());
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容