自定义圆角、圆形图片

支持圆形、圆角(默认4边圆角,支持自定义各个圆角radius)图片。
先建个类RoundImg继承AppCompatImageView ,然后在res-values-attrs(没有attrs的自己创建个attrs的xml文件)添加自定义view可能用到的属性

<declare-styleable name="RoundImg">
        <attr name="isCircle" format="boolean" />
        <attr name="radius" format="dimension" />
        <attr name="leftTop" format="boolean" />
        <attr name="rightTop" format="boolean" />
        <attr name="leftBottom" format="boolean" />
        <attr name="rightBottom" format="boolean" />
    </declare-styleable>

然后就是下面代码,我尽量把注释写详细点

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

import com.eluton.medclass.R;
import com.eluton.utils.LogUtil;


/**
 * Created by admin on 2018/5/10.
 */

public class RoundImg extends AppCompatImageView {

    private Paint paint;
    private float radius = 2;//圆角半径
    private boolean isCircle = true;
    private boolean leftTop = false;//左上部分是否圆角
    private boolean rightTop = false;//右上部分是否圆角
    private boolean leftBottom = false;//左下部分是否圆角
    private boolean rightBottom = false;//右下部分是否圆角

    private int circlePad;//圆形图片的pad

    public void setCirclePad(int circlePad) {
        this.circlePad = circlePad;
    }

    public RoundImg(Context context) {
        this(context, null);
    }

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

    public RoundImg(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        //获取在xml中定义的数据
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RoundImg);
        radius = array.getDimension(R.styleable.RoundImg_radius, 4);
        isCircle = array.getBoolean(R.styleable.RoundImg_isCircle, true);
        leftTop = array.getBoolean(R.styleable.RoundImg_leftTop, false);
        rightTop = array.getBoolean(R.styleable.RoundImg_rightTop, false);
        leftBottom = array.getBoolean(R.styleable.RoundImg_leftBottom, false);
        rightBottom = array.getBoolean(R.styleable.RoundImg_rightBottom, false);
        array.recycle();//拿到记得释放TypedArray 
        paint = new Paint();
    }

    /**
     * 绘制圆角矩形图片
     *
     * @author caizhiming
     */

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if (drawable != null) {
            int width = drawable.getIntrinsicWidth();
            int height = drawable.getIntrinsicHeight();
//            Bitmap bitmap = null;
//            if (drawable instanceof GlideBitmapDrawable) {
//                bitmap = ((GlideBitmapDrawable) drawable).getBitmap();
//            } else {
//                bitmap = ((BitmapDrawable) drawable).getBitmap();
//            }
            Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
            Canvas drawCanvas = new Canvas(bitmap);
            float scale = 1.0f;
            scale = Math.max(getWidth() * 1.0f / width, getHeight()
                    * 1.0f / height);
            drawable.setBounds(0, 0, (int) (scale * width),
                    (int) (scale * height));
            drawable.draw(drawCanvas);
            Bitmap mMaskBitmap;
            if (isCircle) {
                mMaskBitmap = getCircle();
            } else {
                if (leftTop || rightTop || leftBottom || rightBottom) {
                    mMaskBitmap = getPathBitmap();
                } else {
                    mMaskBitmap = getRect();
                }

            }
            paint.setAntiAlias(true);
            if (isCircle) {//给圆形图片外边画白描边
                paint.setColor(getResources().getColor(R.color.white));
                canvas.drawCircle(getWidth() / 2, getWidth() / 2, getWidth() / 2, paint);
            }

            paint.reset();
            paint.setFilterBitmap(false);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

            //绘制形状
            drawCanvas.drawBitmap(mMaskBitmap, 0, 0, paint);

            //绘制图片

            canvas.drawBitmap(bitmap, 0, 0, null);
            paint.setXfermode(null);

        } else {
            super.onDraw(canvas);
        }
    }

    @Override
    public void invalidate() {
        super.invalidate();
    }

    private Bitmap getCircle() {
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(),
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);   //抗锯齿
        paint.setColor(Color.BLACK);
        canvas.drawCircle(getWidth() / 2, getWidth() / 2, getWidth() / 2 - 2, paint);
//getWidth() / 2 - 2 之所以-2,是故意把圆形图片画小一点,到时再画个背景,就成了带描边且描边边距为2px的圆形图片,就是说你描边要多少像素你就减少多少就是。其实我就是懒得把这属性也变成动态的
        return bitmap;
    }

    public Bitmap getRect() {
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(),
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);   //抗锯齿
        paint.setColor(Color.BLACK);
        canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), radius, radius, paint);
        return bitmap;
    }

    private Bitmap getPathBitmap() {
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);   //抗锯齿

        Path path = new Path();
//        LogUtil.i("高度:" + getHeight());
        path.moveTo(0, getHeight() / 2);
        if (leftTop) {
//            LogUtil.i("leftTop");
            path.lineTo(0, radius);
            RectF rectF = new RectF(0, 0, 2 * radius, 2 * radius);
            path.arcTo(rectF, 180, 90);
        } else {
            path.lineTo(0, 0);
        }
        if (rightTop) {
            path.lineTo(getWidth() - radius, 0);
            RectF rectF2 = new RectF(getWidth() - 2 * radius, 0, getWidth(), 2 * radius);
            path.arcTo(rectF2, 270, 90);
        } else {
            path.lineTo(getWidth(), 0);
        }

        if (rightBottom) {
            path.lineTo(getWidth(), getHeight() - radius);
            RectF rectF2 = new RectF(getWidth() - 2 * radius, getHeight() - 2 * radius, getWidth(), getHeight());
            path.arcTo(rectF2, 0, 90);
        } else {
            path.lineTo(getWidth(), getHeight());
        }

        if (leftBottom) {
//            LogUtil.i("leftBottom");
            path.lineTo(radius, getHeight());
            RectF rectF2 = new RectF(0, getHeight() - 2 * radius, 2 * radius, getHeight());
            path.arcTo(rectF2, 90, 90);
        } else {
            path.lineTo(0, getHeight());
        }
        path.lineTo(0, getHeight() / 2);
//        path.moveTo(0, getHeight());
//        path.lineTo(0, getHeight() - radius);
//        RectF rectF = new RectF(0, 0, 2 * radius, 2 * radius);
//        path.arcTo(rectF, 180, 90);
//        path.lineTo(getWidth() - radius, 0);
//        RectF rectF2 = new RectF(getWidth() - 2 * radius, 0, getWidth(), 2 * radius);
//        path.arcTo(rectF2, 270, 90);
//        path.lineTo(getWidth(), getHeight());
//        path.lineTo(0, getHeight());
        canvas.drawPath(path, paint);
        return bitmap;
    }

}

直接在xml使用就行,在xml最外层加入 xmlns:app="http://schemas.android.com/apk/res-auto",这样才能调用自定义的view属性

 <com.eluton.view.RoundImg
            android:id="@+id/img_user"
            android:layout_width="24dp"
            android:layout_height="24dp"
            app:isCircle="false"
            android:scaleType="fitCenter"
            android:src="@mipmap/appicon" />

app:isCircle="false"表示圆角图片,默认圆形图片,其他属性按自己需要添加就是。android:scaleType="fitCenter"是图片填充方式,根据自己需要修改就是

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