Android自定义图片圆角,增加渐变阴影

自定义图片,切圆角、圆形,增加渐变颜色阴影


一、先上效果图

效果图

二、GitHub

代码地址,欢迎指正https://github.com/MNXP/RoundImageView

三、思路

 1、图片切成圆角(圆形)
 2、绘制一个带有渐变阴影的图形
 3、融合圆角图片和阴影图形

四、实现(以下是以圆角为例,圆形的类似)

1)图片切成圆角

 BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
 Bitmap targetBitmap = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
 Canvas targetCanvas = new Canvas(targetBitmap);
 mPaint.setShader(bitmapShader);
 RectF rect = new RectF(0, 0, imageWidth, imageHeight);
 targetCanvas.drawRoundRect(rect, mRadius, mRadius, mPaint);
 形成的效果图
圆角

2)绘制一个带有渐变阴影的图形

设置渐变阴影 mPaint.setShadowLayer(mShadowRadius, 1, 1, mShadowColor); 
第一个参数:阴影大小;
第二个参数:X轴偏移量;
第三个参数:Y轴偏移量;
第四个参数:阴影颜色;
X、Y轴偏移量都为1时是四周都有阴影

设置paint的颜色和阴影颜色一致,不然会出现黑边   mPaint.setColor(mShadowColor);
  mPaint.setColor(mShadowColor);
  mPaint.setShadowLayer(mShadowRadius, 1, 1, mShadowColor);
  Bitmap target = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(target);
  RectF rectF = new RectF(mShadowRadius, mShadowRadius, width - mShadowRadius, height - mShadowRadius);
  canvas.drawRoundRect(rectF, mRadius, mRadius, mPaint);
阴影效果图

3)融合圆角图片和阴影图形

上代码之前先上一个图像合成效果示意图
图像合成效果示意图
 好了,上面就是图像融合的一些方式,我用的是SRC_OVER。记得把paint设置的shadowLayer去掉
  mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
  mPaint.setShadowLayer(0, 0, 0, 0xffffff);
  canvas.drawBitmap(targetBitmap, mShadowRadius, mShadowRadius, mPaint);
最终效果图

4)使用(就是这么简单)

<declare-styleable name="RoundImageView">
    <attr name="image_radius" format="dimension" />//圆角大小
    <attr name="image_shadow_radius" format="dimension" />//阴影大小
    <attr name="image_circle" format="boolean" />//是否圆形
    <attr name="image_shadow" format="boolean" />//是否阴影
    <attr name="shadow_color" format="integer"/>//阴影颜色
</declare-styleable>


<com.xiangpan.roundimageview.RoundImageView
    android:layout_width="300dp"
    android:layout_height="200dp"
    android:layout_gravity="center_horizontal"
    android:src="@mipmap/tu"
    app:image_shadow="true"
    app:image_radius = "16dp"
    app:image_shadow_radius="20dp"/>

5)注意

  因为绘制,阴影也会算入控件的大小
示意图
初始化参数
width = canvas.getWidth() - getPaddingLeft() - getPaddingRight();//控件实际大小
height = canvas.getHeight() - getPaddingTop() - getPaddingBottom();
if (!mIsShadow)
     mShadowRadius = 0;
imageWidth = width - (int) mShadowRadius * 2;//图片实际宽度
imageHeight = height - (int) mShadowRadius * 2;//图片实际高度
Bitmap image = drawableToBitmap(getDrawable());
Bitmap reSizeImage = reSizeImage(image, imageWidth, imageHeight);

6)RoundImageView完整代码


public class RoundImageView extends AppCompatImageView {


    public RoundImageView(final Context context) {
        this(context, null);
    }

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

    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.setScaleType(ScaleType.FIT_XY);
        TypedArray ta = context.obtainStyledAttributes(attrs,
                R.styleable.RoundImageView, defStyle, 0);
        if (ta!=null){
            mRadius = ta.getDimension(R.styleable.RoundImageView_image_radius, 0);
            mShadowRadius = ta.getDimension(R.styleable.RoundImageView_image_shadow_radius, 0);
            mIsCircle = ta.getBoolean(R.styleable.RoundImageView_image_circle, false);
            mIsShadow = ta.getBoolean(R.styleable.RoundImageView_image_shadow, false);
            mShadowColor = ta.getInteger(R.styleable.RoundImageView_shadow_color,0xffe4e4e4);
            ta.recycle();
        }else {
            mRadius = 0;
            mShadowRadius = 0;
            mIsCircle = false;
            mIsShadow = false;
            mShadowColor = 0xffe4e4e4;
        }

    }


    private float mRadius;
    private float mShadowRadius;
    private int mShadowColor;
    private boolean mIsCircle;
    private boolean mIsShadow;
    private int width;
    private int height;
    private int imageWidth;
    private int imageHeight;
    private Paint mPaint;

    @Override
    public void onDraw(Canvas canvas) {
        width = canvas.getWidth() - getPaddingLeft() - getPaddingRight();//控件实际大小
        height = canvas.getHeight() - getPaddingTop() - getPaddingBottom();

        if (!mIsShadow)
            mShadowRadius = 0;

        imageWidth = width - (int) mShadowRadius * 2;
        imageHeight = height - (int) mShadowRadius * 2;

        Bitmap image = drawableToBitmap(getDrawable());
        Bitmap reSizeImage = reSizeImage(image, imageWidth, imageHeight);
        initPaint();


        if (mIsCircle) {
            canvas.drawBitmap(createCircleImage(reSizeImage),
                    getPaddingLeft(), getPaddingTop(), null);

        } else {
            canvas.drawBitmap(createRoundImage(reSizeImage),
                    getPaddingLeft(), getPaddingTop(), null);
        }
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
    }


    private Bitmap createRoundImage(Bitmap bitmap) {
        if (bitmap == null) {
            throw new NullPointerException("Bitmap can't be null");
        }
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        Bitmap targetBitmap = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
        Canvas targetCanvas = new Canvas(targetBitmap);

        mPaint.setShader(bitmapShader);

        RectF rect = new RectF(0, 0, imageWidth, imageHeight);
        targetCanvas.drawRoundRect(rect, mRadius, mRadius, mPaint);

        if (mIsShadow){
            mPaint.setShader(null);
            mPaint.setColor(mShadowColor);
            mPaint.setShadowLayer(mShadowRadius, 1, 1, mShadowColor);
            Bitmap target = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(target);

            RectF rectF = new RectF(mShadowRadius, mShadowRadius, width - mShadowRadius, height - mShadowRadius);
            canvas.drawRoundRect(rectF, mRadius, mRadius, mPaint);
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
            mPaint.setShadowLayer(0, 0, 0, 0xffffff);
            canvas.drawBitmap(targetBitmap, mShadowRadius, mShadowRadius, mPaint);
            return target;
        }else {
            return targetBitmap;
        }

    }


    private Bitmap createCircleImage(Bitmap bitmap) {
        if (bitmap == null) {
            throw new NullPointerException("Bitmap can't be null");
        }
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        Bitmap targetBitmap = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
        Canvas targetCanvas = new Canvas(targetBitmap);

        mPaint.setShader(bitmapShader);

        targetCanvas.drawCircle(imageWidth / 2, imageWidth / 2, Math.min(imageWidth, imageHeight) / 2,
                mPaint);

        if (mIsShadow){
            mPaint.setShader(null);
            mPaint.setColor(mShadowColor);
            mPaint.setShadowLayer(mShadowRadius, 1, 1, mShadowColor);
            Bitmap target = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(target);

            canvas.drawCircle(width / 2, height / 2, Math.min(imageWidth, imageHeight) / 2,
                    mPaint);
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
            mPaint.setShadowLayer(0, 0, 0, 0xffffff);
            canvas.drawBitmap(targetBitmap, mShadowRadius, mShadowRadius, mPaint);
            return target;
        }else {
            return targetBitmap;
        }

    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    /**
     * drawable转bitmap
     *
     * @param drawable
     * @return
     */
    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable == null) {
            return null;
        } else if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicHeight(),
                drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 重设Bitmap的宽高
     *
     * @param bitmap
     * @param newWidth
     * @param newHeight
     * @return
     */
    private Bitmap reSizeImage(Bitmap bitmap, int newWidth, int newHeight) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        // 计算出缩放比
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 矩阵缩放bitmap
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    }


}


如有意见和建议,及时沟通。

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

推荐阅读更多精彩内容