1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Android ImageView到底怎么设置圆角图片?背景圆角?控件圆角?图片圆角?占位图圆角?

Android ImageView到底怎么设置圆角图片?背景圆角?控件圆角?图片圆角?占位图圆角?

时间:2021-12-07 10:48:28

相关推荐

Android ImageView到底怎么设置圆角图片?背景圆角?控件圆角?图片圆角?占位图圆角?

前言

在我们实际开发应用的过程中,我想大家或多或少都遇到过需要加载圆角图片的场景,还有一些图片是四周圆角不对称,异性圆角等等情况。

我们可能会去网上或Github上搜索一些RoundImageView之类的第三方自定义View,有效果就行,如果没有效果就换一个库,总有能行的库是吧。

我早几年前做项目就遇到这样的场景,设置背景之后,在上面加载圆角的图片,但是背景会漏出来,好不容易让UI切图解决之后,占位图又出问题,占位图不是圆角的就把整个布局盖住了,不符合UI的美学,哎,我要吐了。

我们需要了解他们的大致原理,加载圆角的图片有几种思路,每一种思路又又几种实现的方案?各种方案如何实现的?有什么差异?

其实圆角图片的加载有两种思路,一种是加载的过程中对Bitmap做裁剪,另一种是Bitmap没有裁剪,但是对ImageView显示的时候做裁剪。

例如第一种思路,我们使用Glide图片加载库来处理圆角。

例如第二种思路,我们常用RoundImageView之类的自定义View来实现。

而第二种思路又有不同的方案实现,兼容性和目标性也不一致,如果你找到的第三库不能达到全部的效果,那应该怎么办?

所以现在我就要想一个通用的解决方案,我想要背景圆角,占位图圆角,图片内容圆角,全部的功能,我全都想要!

话不多说,先看看自定义ImageView的几种方案的简单示例。

一、几种圆角ImageView的定义方式

通常来说,我们定义一个控件的圆角裁剪有三种方案。ClipPathXfermodeShader

(PS.其实还有一种ViewOutlineProvider 的方案,由于要求21以上才能用,所以这里没有统计)

下面我们看看三者分别如何定义:

ClipPath 直接剪辑路线:

public class ClipPathRoundImageView extends AppCompatImageView {float width, height;private int mRoundRadius = CommUtils.dip2px(15);public ClipPathRoundImageView(Context context) {this(context, null);}public ClipPathRoundImageView(Context context, AttributeSet attrs) {this(context, attrs, 0);}public ClipPathRoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);//在api11到api18之间设置禁用硬件加速if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {setLayerType(LAYER_TYPE_SOFTWARE, null);}}@Overrideprotected void onLayout(boolean changed, int left, int top, int right, int bottom) {super.onLayout(changed, left, top, right, bottom);width = getWidth();height = getHeight();}@Overrideprotected void onDraw(Canvas canvas) {if (width > mRoundRadius && height > mRoundRadius) {Path path = new Path();path.moveTo(mRoundRadius, 0);path.lineTo(width - mRoundRadius, 0); //上侧的横线path.quadTo(width, 0, width, mRoundRadius); //右上的圆弧曲线path.lineTo(width, height - mRoundRadius); //右侧的直线path.quadTo(width, height, width - mRoundRadius, height); //右下的圆弧曲线path.lineTo(mRoundRadius, height); //下侧的横线path.quadTo(0, height, 0, height - mRoundRadius); //左下的圆弧曲线path.lineTo(0, mRoundRadius); //左侧的直线path.quadTo(0, 0, mRoundRadius, 0); //左上的圆弧曲线canvas.clipPath(path);}super.onDraw(canvas);}}复制代码

Xfermode 设置混合模式:

public class XfermodeRoundImageView extends AppCompatImageView {private Paint mPaint;private Xfermode mXfermode;private int mRoundRadius = CommUtils.dip2px(15);public XfermodeRoundImageView(Context context) {this(context, null);}public XfermodeRoundImageView(Context context, AttributeSet attrs) {this(context, attrs, 0);}public XfermodeRoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);//在api11到api18之间设置禁用硬件加速if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {setLayerType(LAYER_TYPE_SOFTWARE, null);}mPaint = new Paint();mPaint.setAntiAlias(true);mXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);}@Overrideprotected void onDraw(Canvas canvas) {if (getDrawable() == null) {return;}int sc = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);//画源图像,为一个圆角矩形canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), mRoundRadius, mRoundRadius, mPaint);//设置混合模式mPaint.setXfermode(mXfermode);//画目标图像canvas.drawBitmap(drawableToBitamp(exChangeSize(getDrawable())), 0, 0, mPaint);// 还原混合模式mPaint.setXfermode(null);canvas.restoreToCount(sc);}/*** 图片拉升*/private Drawable exChangeSize(Drawable drawable) {float scale = 1.0f;scale = Math.max(getWidth() * 1.0f / drawable.getIntrinsicWidth(), getHeight()* 1.0f / drawable.getIntrinsicHeight());drawable.setBounds(0, 0, (int) (scale * drawable.getIntrinsicWidth()),(int) (scale * drawable.getIntrinsicHeight()));return drawable;}private Bitmap drawableToBitamp(Drawable drawable) {if (drawable instanceof BitmapDrawable) {BitmapDrawable bd = (BitmapDrawable) drawable;return bd.getBitmap();}int w = drawable.getIntrinsicWidth() <= 0 ? getWidth() : drawable.getIntrinsicWidth();int h = drawable.getIntrinsicHeight() <= 0 ? getHeight() : drawable.getIntrinsicHeight();Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(bitmap);drawable.setBounds(0, 0, w, h);drawable.draw(canvas);return bitmap;}}复制代码

BitmapShader 指定范围渲染

public class ShaderRoundImageView extends AppCompatImageView {//圆角大小,默认为10private int mRoundRadius = CommUtils.dip2px(15);private Paint mPaint;// 3x3 矩阵,主要用于缩小放大private Matrix mMatrix;//渲染图像,使用图像为绘制图形着色private BitmapShader mBitmapShader;public ShaderRoundImageView(Context context) {this(context, null);}public ShaderRoundImageView(Context context, AttributeSet attrs) {this(context, attrs, 0);}public ShaderRoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);mMatrix = new Matrix();mPaint = new Paint();mPaint.setAntiAlias(true);}@Overrideprotected void onDraw(Canvas canvas) {if (getDrawable() == null) {return;}Bitmap bitmap = drawableToBitamp(getDrawable());mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);float scale = 1.0f;if (!(bitmap.getWidth() == getWidth() && bitmap.getHeight() == getHeight())) {// 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值;scale = Math.max(getWidth() * 1.0f / bitmap.getWidth(),getHeight() * 1.0f / bitmap.getHeight());}// shader的变换矩阵,我们这里主要用于放大或者缩小mMatrix.setScale(scale, scale);// 设置变换矩阵mBitmapShader.setLocalMatrix(mMatrix);// 设置shadermPaint.setShader(mBitmapShader);canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), mRoundRadius, mRoundRadius, mPaint);}private Bitmap drawableToBitamp(Drawable drawable) {if (drawable instanceof BitmapDrawable) {BitmapDrawable bd = (BitmapDrawable) drawable;return bd.getBitmap();}int w = drawable.getIntrinsicWidth() <= 0 ? getWidth() : drawable.getIntrinsicWidth();int h = drawable.getIntrinsicHeight() <= 0 ? getHeight() : drawable.getIntrinsicHeight();Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(bitmap);drawable.setBounds(0, 0, w, h);drawable.draw(canvas);return bitmap;}}复制代码

前两种方案在一些版本中需要配合关闭硬件加速,BitmapShared的方案兼容性更好。

在xml中的顺序如下

效果:

此时我们加载网络图片,并且不设置裁剪模式,我们加上圆形的图片做对比,他们的展示如下:

加上裁剪模式为居中裁剪之后,他们的效果如下:

简单的使用确实是可以用了。

如果加上backgroundColor之后呢?

丑,背景无法裁剪!这个问题后面单独再说。

那如果我们不使用自定义View,就是默认的ImageView,我们还能不能实现图片圆角的展示?

二、内容圆角之Glide的transforms

当然可以,我们可以直接对Bitmap操作,裁剪Bitmap得到一个圆角的Bitmap。

例如我们常用的Glide图片加载框架,我们可以通过transforms的转换得到对应的圆角图片

transforms(CenterCrop(), RoundedCorners(roundRadius))复制代码

具体执行的源码如下

public static Bitmap roundedCorners(@NonNull BitmapPool pool, @NonNull Bitmap inBitmap, final int roundingRadius) {Preconditions.checkArgument(roundingRadius > 0, "roundingRadius must be greater than 0.");return roundedCorners(pool,inBitmap,new DrawRoundedCornerFn() {@Overridepublic void drawRoundedCorners(Canvas canvas, Paint paint, RectF rect) {canvas.drawRoundRect(rect, roundingRadius, roundingRadius, paint);}});}public static Bitmap roundedCorners(@NonNull BitmapPool pool,@NonNull Bitmap inBitmap,final float topLeft,final float topRight,final float bottomRight,final float bottomLeft) {return roundedCorners(pool,inBitmap,new DrawRoundedCornerFn() {@Overridepublic void drawRoundedCorners(Canvas canvas, Paint paint, RectF rect) {Path path = new Path();path.addRoundRect(rect,new float[] {topLeft,topLeft,topRight,topRight,bottomRight,bottomRight,bottomLeft,bottomLeft},Path.Direction.CW);canvas.drawPath(path, paint);}});}复制代码

一种是四角固定圆角,一种是分别设置圆角。我们对比一下效果:

效果:

确实是可以达到效果,背景一样无法裁剪。可以想象,但是这种情况有一种问题,就是占位图的问题,由于ImageView就是一个标准的正方形,所以如果我们使用统一的长方形占位图,那么就会出现问题。

明明我想要的是圆角20的图片,可是占位图确实方的,如果是错误图片,就会觉得很突兀。

可以看到只有第一种方案的圆角ImageView,它的占位图是符合想象的。

三、如何设置圆角背景与占位图

如何设置圆角的背景与占位图呢?

最简单的,找UI去切图,每一个比例,每一个圆角,都可以要对应的占位图和背景图。也是我们最常用的方式。使用一个圆角的父容器包裹一层,由于父容器裁剪了展示的范围,所以子ImageView作为一个正常的非自定义View就可以方便的实现各种圆角。但是这种方案嵌套了一层,并且在需求复杂的情况下,比如各个圆角不同的方案下使用相对麻烦。自定义RoundImageView,做一个自己的背景,不使用View的setBackground,或者重写View的setBackground,去调用自己的背景方法,自己的背景方法中我们自己draw一个背景的图层。

这里演示的是第三种方案,我们自己先 draw 一个rect当背景,然后再 draw 一个指定的Bitmap当内容,即可实现效果。部分核心代码如下:

@Overridepublic void setBackgroundColor(int color) {setRoundBackgroundColor(color);}public int getRoundBackgroundColor() {return mRoundBackgroundColor;}public void setRoundBackgroundColor(@ColorInt int roundBackgroundColor) {if (roundBackgroundColor == mRoundBackgroundColor) {return;}mRoundBackgroundColor = roundBackgroundColor;mRoundBackgroundPaint.setColor(roundBackgroundColor);invalidate();}public void setRoundBackgroundColorResource(@ColorRes int circleBackgroundRes) {setRoundBackgroundColor(getContext().getResources().getColor(circleBackgroundRes));}private void init(){mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);mBitmapPaint.setAntiAlias(true);mBitmapPaint.setShader(mBitmapShader);mRoundBackgroundPaint.setStyle(Paint.Style.FILL);mRoundBackgroundPaint.setAntiAlias(true);mRoundBackgroundPaint.setColor(mRoundBackgroundColor);}@Overrideprotected void onDraw(Canvas canvas) {if (mBitmap == null) {return;}if (mRoundBackgroundColor != Color.TRANSPARENT) {canvas.drawRoundRect(mDrawableRect, mRoundRadius, mRoundRadius, mRoundBackgroundPaint);}canvas.drawRoundRect(mDrawableRect, mRoundRadius, mRoundRadius, mBitmapPaint);}复制代码

这里我只做了背景color的用法,如果想要drawable背景的话,也是一样的道理那我们drawBackground的时候就是draw一个背景的bitmap即可,和内容Bitmap的绘制类似。

效果:

占位图:

四、如何设置四个角不同圆角

看到之前我们的三种方案,大部分都是在 drawRoundRect 既然是这样那么就只能保证一种圆角角度,如果想四个角分别是不同的圆角,那么我们就只能用其中 clipPath 的方案,它是Path的路径绘制,可以很方便的按照路径裁剪指定的圆角。

我们自定义View如下:

/*** 可以自定义四个角的不同的圆角值*/public class CustomRadiusImageView extends AppCompatImageView {private float width, height;private int defaultRadius = 0;private int radius;private int leftTopRadius;private int rightTopRadius;private int rightBottomRadius;private int leftBottomRadius;public CustomRadiusImageView(Context context) {this(context, null);init(context, null);}public CustomRadiusImageView(Context context, AttributeSet attrs) {this(context, attrs, 0);init(context, attrs);}public CustomRadiusImageView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);init(context, attrs);}private void init(Context context, AttributeSet attrs) {//在api11到api18之间设置禁用硬件加速if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {setLayerType(LAYER_TYPE_SOFTWARE, null);}//读取配置属性TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomRadiusImageView);radius = array.getDimensionPixelOffset(R.styleable.CustomRadiusImageView_radius, defaultRadius);leftTopRadius = array.getDimensionPixelOffset(R.styleable.CustomRadiusImageView_left_top_radius, defaultRadius);rightTopRadius = array.getDimensionPixelOffset(R.styleable.CustomRadiusImageView_right_top_radius, defaultRadius);rightBottomRadius = array.getDimensionPixelOffset(R.styleable.CustomRadiusImageView_right_bottom_radius, defaultRadius);leftBottomRadius = array.getDimensionPixelOffset(R.styleable.CustomRadiusImageView_left_bottom_radius, defaultRadius);//设置四个角的默认圆角值if (defaultRadius == leftTopRadius) {leftTopRadius = radius;}if (defaultRadius == rightTopRadius) {rightTopRadius = radius;}if (defaultRadius == rightBottomRadius) {rightBottomRadius = radius;}if (defaultRadius == leftBottomRadius) {leftBottomRadius = radius;}array.recycle();}@Overrideprotected void onLayout(boolean changed, int left, int top, int right, int bottom) {super.onLayout(changed, left, top, right, bottom);width = getWidth();height = getHeight();}@Overrideprotected void onDraw(Canvas canvas) {int maxLeft = Math.max(leftTopRadius, leftBottomRadius);int maxRight = Math.max(rightTopRadius, rightBottomRadius);int minWidth = maxLeft + maxRight;int maxTop = Math.max(leftTopRadius, rightTopRadius);int maxBottom = Math.max(leftBottomRadius, rightBottomRadius);int minHeight = maxTop + maxBottom;if (width >= minWidth && height > minHeight) {Path path = new Path();path.moveTo(leftTopRadius, 0);path.lineTo(width - rightTopRadius, 0);path.quadTo(width, 0, width, rightTopRadius);path.lineTo(width, height - rightBottomRadius);path.quadTo(width, height, width - rightBottomRadius, height);path.lineTo(leftBottomRadius, height);path.quadTo(0, height, 0, height - leftBottomRadius);path.lineTo(0, leftTopRadius);path.quadTo(0, 0, leftTopRadius, 0);canvas.clipPath(path);}super.onDraw(canvas);}}复制代码

使用:

效果:

可以看到除了背景无法圆角之外,可以完美的满足我们的需求了?为什么背景无法设置,因为背景无法通过 drawRoundRect 绘制出来,Bitmap也不能通过 drawRoundRect 绘制不同的圆角。

之前我们讲过,其实三种方案 Shader 的兼容性是相对较好的,那我们就想通过Shader的方案来绘制不同的圆角Bitmap,顺便绘制我们的自定义背景不就完美解决问题了吗?

问题就来到如何绘制不同圆角上来了,我们都知道drawCircle drawRect drawRoundRect来绘制一些简单的规则的图形,如果是不规则的图形,我们就需要用到DrawPath来完成,我们把Path中指定Rect的时候指定不同的圆角不就行了吗,然后再通过drawPath绘制出来。

核心代码如下:

Path path = new Path();path.addRoundRect(mDrawableRect,new float[]{mTopLeft, mTopLeft, mTopRight, mTopRight, mBottomRight, mBottomRight, mBottomLeft, mBottomLeft},Path.Direction.CW);canvas.drawPath(path, mBitmapPaint);复制代码

我们就能使用 Shader 的方案来实现自定义圆角View,这是最完美的方案,我们可以设置背景圆角,控件圆角,还能指定各自的圆角角度。

使用:

上面的加载图片,下面的加载占位图,两者都已经设置了背景

findViewById<RoundCircleImageView>(R.id.iv_custom_round).setRoundBackgroundColorResource(R.color.picture_color_blue)findViewById<RoundCircleImageView>(R.id.iv_custom_round).extLoad(imgUrl, R.drawable.test_img_placeholder)findViewById<RoundCircleImageView>(R.id.iv_custom_round2).setRoundBackgroundColorResource(R.color.picture_color_blue)findViewById<RoundCircleImageView>(R.id.iv_custom_round2).extLoad("123", R.drawable.test_img_placeholder)复制代码

效果:

五、推荐的最佳方案方案完整代码

在 Shader 方案的基础上,我们实现了一些简单的实现,现在我们进一步封装。

我们顺便加上圆形图片的绘制,圆角的图片绘制,各自圆角的绘制,和对应的背景的圆角,图片背景与颜色背景设置等一系列功能。

/*** 只能支持四周固定的圆角,或者圆形的图片* 支持设置自定义圆角或圆形背景颜色,(需要使用当前类提供的背景颜色方法)* <p>* 支持四个角各自定义角度*/public class RoundCircleImageView extends AppCompatImageView {private int mRoundRadius = 0;private boolean isCircleType;private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;private static final int COLORDRAWABLE_DIMENSION = 2;private final RectF mDrawableRect = new RectF();private final Matrix mShaderMatrix = new Matrix();private final Paint mBitmapPaint = new Paint();private final Paint mRoundBackgroundPaint = new Paint();private Drawable mRoundBackgroundDrawable;private Bitmap mBitmap;private BitmapShader mBitmapShader;private int mBitmapWidth;private int mBitmapHeight;private Bitmap mBackgroundBitmap;private BitmapShader mBackgroundBitmapShader;private ColorFilter mColorFilter;private float mDrawableRadius;private boolean mReady;private boolean mSetupPending;private float mTopLeft;private float mTopRight;private float mBottomLeft;private float mBottomRight;public RoundCircleImageView(Context context) {super(context);init();}public RoundCircleImageView(Context context, AttributeSet attrs) {this(context, attrs, 0);}public RoundCircleImageView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);//读取配置属性TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RoundCircleImageView);mRoundRadius = array.getDimensionPixelOffset(R.styleable.RoundCircleImageView_round_radius, 0);mTopLeft = array.getDimensionPixelOffset(R.styleable.RoundCircleImageView_topLeft, 0);mTopRight = array.getDimensionPixelOffset(R.styleable.RoundCircleImageView_topRight, 0);mBottomLeft = array.getDimensionPixelOffset(R.styleable.RoundCircleImageView_bottomLeft, 0);mBottomRight = array.getDimensionPixelOffset(R.styleable.RoundCircleImageView_bottomRight, 0);if (array.hasValue(R.styleable.RoundCircleImageView_round_background_color)) {int roundBackgroundColor = array.getColor(R.styleable.RoundCircleImageView_round_background_color, Color.TRANSPARENT);mRoundBackgroundDrawable = new ColorDrawable(roundBackgroundColor);mBackgroundBitmap = getBitmapFromDrawable(mRoundBackgroundDrawable);}if (array.hasValue(R.styleable.RoundCircleImageView_round_background_drawable)) {mRoundBackgroundDrawable = array.getDrawable(R.styleable.RoundCircleImageView_round_background_drawable);mBackgroundBitmap = getBitmapFromDrawable(mRoundBackgroundDrawable);}isCircleType = array.getBoolean(R.styleable.RoundCircleImageView_isCircle, false);array.recycle();init();}private void init() {super.setScaleType(SCALE_TYPE);mReady = true;if (mSetupPending) {setup();mSetupPending = false;}}@Overridepublic ScaleType getScaleType() {return SCALE_TYPE;}@Overridepublic void setScaleType(ScaleType scaleType) {if (scaleType != SCALE_TYPE) {throw new IllegalArgumentException("已经自带设置了,你无需再设置了");}}@Overridepublic void setAdjustViewBounds(boolean adjustViewBounds) {if (adjustViewBounds) {throw new IllegalArgumentException("已经自带设置了,你无需再设置了");}}@SuppressLint("DrawAllocation")@Overrideprotected void onDraw(Canvas canvas) {if (mBitmap == null && mBackgroundBitmap == null) {return;}if (isCircleType) {if (mRoundBackgroundDrawable != null && mBackgroundBitmap != null) {canvas.drawCircle(mDrawableRect.centerX(), mDrawableRect.centerY(), mDrawableRadius, mRoundBackgroundPaint);}if (mBitmap != null) {canvas.drawCircle(mDrawableRect.centerX(), mDrawableRect.centerY(), mDrawableRadius, mBitmapPaint);}} else {if (mTopLeft > 0 || mTopRight > 0 || mBottomLeft > 0 || mBottomRight > 0) {//使用单独的圆角if (mRoundBackgroundDrawable != null && mBackgroundBitmap != null) {Path path = new Path();path.addRoundRect(mDrawableRect,new float[]{mTopLeft, mTopLeft, mTopRight, mTopRight, mBottomRight, mBottomRight, mBottomLeft, mBottomLeft},Path.Direction.CW);canvas.drawPath(path, mRoundBackgroundPaint);}if (mBitmap != null) {Path path = new Path();path.addRoundRect(mDrawableRect,new float[]{mTopLeft, mTopLeft, mTopRight, mTopRight, mBottomRight, mBottomRight, mBottomLeft, mBottomLeft},Path.Direction.CW);canvas.drawPath(path, mBitmapPaint);}} else {//使用统一的圆角if (mRoundBackgroundDrawable != null && mBackgroundBitmap != null) {canvas.drawRoundRect(mDrawableRect, mRoundRadius, mRoundRadius, mRoundBackgroundPaint);}if (mBitmap != null) {canvas.drawRoundRect(mDrawableRect, mRoundRadius, mRoundRadius, mBitmapPaint);}}}}@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) {super.onSizeChanged(w, h, oldw, oldh);setup();}@Overridepublic void setPadding(int left, int top, int right, int bottom) {super.setPadding(left, top, right, bottom);setup();}@Overridepublic void setPaddingRelative(int start, int top, int end, int bottom) {super.setPaddingRelative(start, top, end, bottom);setup();}@Overridepublic void setBackgroundColor(int color) {setRoundBackgroundColor(color);}@Overridepublic void setBackground(Drawable background) {setRoundBackgroundDrawable(background);}@Overridepublic void setBackgroundDrawable(@Nullable Drawable background) {setRoundBackgroundDrawable(background);}@Overridepublic void setBackgroundResource(int resId) {@SuppressLint("UseCompatLoadingForDrawables")Drawable drawable = getContext().getResources().getDrawable(resId);setRoundBackgroundDrawable(drawable);}@Overridepublic Drawable getBackground() {return getRoundBackgroundDrawable();}public void setRoundBackgroundColor(@ColorInt int roundBackgroundColor) {ColorDrawable drawable = new ColorDrawable(roundBackgroundColor);setRoundBackgroundDrawable(drawable);}public void setRoundBackgroundColorResource(@ColorRes int circleBackgroundRes) {setRoundBackgroundColor(getContext().getResources().getColor(circleBackgroundRes));}public Drawable getRoundBackgroundDrawable() {return mRoundBackgroundDrawable;}public void setRoundBackgroundDrawable(Drawable drawable) {mRoundBackgroundDrawable = drawable;initializeBitmap();}@Overridepublic void setImageBitmap(Bitmap bm) {super.setImageBitmap(bm);initializeBitmap();}@Overridepublic void setImageDrawable(Drawable drawable) {super.setImageDrawable(drawable);initializeBitmap();}@Overridepublic void setImageResource(@DrawableRes int resId) {super.setImageResource(resId);initializeBitmap();}@Overridepublic void setImageURI(Uri uri) {super.setImageURI(uri);initializeBitmap();}@Overridepublic void setColorFilter(ColorFilter cf) {if (cf == mColorFilter) {return;}mColorFilter = cf;applyColorFilter();invalidate();}@Overridepublic ColorFilter getColorFilter() {return mColorFilter;}private void applyColorFilter() {if (mBitmapPaint != null) {mBitmapPaint.setColorFilter(mColorFilter);}}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 {bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);}Canvas canvas = new Canvas(bitmap);drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());drawable.draw(canvas);return bitmap;} catch (Exception e) {e.printStackTrace();return null;}}private void initializeBitmap() {mBitmap = getBitmapFromDrawable(getDrawable());if (mRoundBackgroundDrawable != null) {mBackgroundBitmap = getBitmapFromDrawable(mRoundBackgroundDrawable);}setup();}private void setup() {if (!mReady) {mSetupPending = true;return;}if (getWidth() == 0 && getHeight() == 0) {return;}if (mBitmap == null && mBackgroundBitmap == null) {invalidate();return;}if (mBitmap != null) {mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);mBitmapPaint.setAntiAlias(true);mBitmapPaint.setShader(mBitmapShader);}if (mRoundBackgroundDrawable != null && mBackgroundBitmap != null) {mBackgroundBitmapShader = new BitmapShader(mBackgroundBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);mRoundBackgroundPaint.setAntiAlias(true);mRoundBackgroundPaint.setShader(mBackgroundBitmapShader);}Bitmap bitmap = mBitmap != null ? mBitmap : mBackgroundBitmap;mBitmapHeight = bitmap.getHeight();mBitmapWidth = bitmap.getWidth();mDrawableRect.set(calculateBounds());mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f);applyColorFilter();updateShaderMatrix();//重绘invalidate();}private RectF calculateBounds() {int availableWidth = getWidth() - getPaddingLeft() - getPaddingRight();int availableHeight = getHeight() - getPaddingTop() - getPaddingBottom();int sideLength = Math.min(availableWidth, availableHeight);float left = getPaddingLeft() + (availableWidth - sideLength) / 2f;float top = getPaddingTop() + (availableHeight - sideLength) / 2f;return new RectF(left, top, left + sideLength, top + sideLength);}private void updateShaderMatrix() {float scale;float dx = 0;float dy = 0;mShaderMatrix.set(null);if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {scale = mDrawableRect.height() / (float) mBitmapHeight;dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;} else {scale = mDrawableRect.width() / (float) mBitmapWidth;dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;}mShaderMatrix.setScale(scale, scale);mShaderMatrix.postTranslate((int) (dx + 0.5f) + mDrawableRect.left, (int) (dy + 0.5f) + mDrawableRect.top);if (mBitmapShader != null) {mBitmapShader.setLocalMatrix(mShaderMatrix);}if (mBackgroundBitmapShader != null) {mBackgroundBitmapShader.setLocalMatrix(mShaderMatrix);}}}复制代码

自定义属性:

<!-- 自定义圆角布局 ,可以设置圆角,圆形 --><declare-styleable name="RoundCircleImageView"><attr name="isCircle" format="boolean" /><attr name="round_background_color" format="color" /><attr name="round_background_drawable" format="reference" /><attr name="round_radius" format="dimension" /><attr name="topLeft" format="dimension" /><attr name="topRight" format="dimension" /><attr name="bottomRight" format="dimension" /><attr name="bottomLeft" format="dimension" /></declare-styleable>复制代码

由于设置图片与占位图上面都已经展示过了,这里只演示背景设置的效果:

支持xml设置

效果:

分别是设置ColorDrawable、Drawable、Color 三种设置方式。

同时也支持代码中设置:

findViewById<RoundCircleImageView>(R.id.iv_custom_round).background = drawable(R.drawable.shape_blue)findViewById<RoundCircleImageView>(R.id.iv_custom_round2).background = drawable(R.drawable.chengxiao)复制代码

有需要可以直接拿走,这应该是非常好用的实战可用的RoundImageView了。如果觉得复制都嫌麻烦,可以去下面查看源码获取。

总结

目前来说想要展示圆角的图片,我们就是两种思路。

在图片加载的过程中,直接对Bitmap做处理,得到一个圆角的Bitmap。加载到对应的ImageView中。图片加载的是标准的图片,通过自定义View的方式,裁剪显示的区域,从而到达看起来圆角图片的效果。

总的来说这两种思路都可以达到目标,但是又有一点差异,大家注意一下两种方案都可用,自己选择即可。

第一种思路:对背景和占位图有需求,最好是找UI切图,对应的比例的圆角背景图和圆角占位图,如果一个项目有多个不同的比例的,不同圆角的设计图,那么可以想象项目中需要导入多少图片,Apk会变大。

第二种思路:我们直接使用默认的一个背景,和一个默认的占位图,让自定义View去居中裁剪展示背景与占位图,相对来说简单一点,但是需要注意的是这样的自定义View网上太多方案,不知道哪一种好,所以本篇文章就是围绕这一点展开。

自定义View终极方案是 BitmapShader 的方案,围绕这一点又封装了一套自定义View。支持设置圆形图片、背景、占位图。支持圆角图片、背景、占位图。还支持了四周不同圆角的设置。

所以大家的项目中都是用的哪一种思路,又是哪一种方案呢?

本文全部代码均以开源,源码在此。大家可以点个Star关注一波。

单独的 RoundCircleImageView 的源码在此。如果不想Copy代码,我已经把代码推到 MavenCentral ,大家也可以使用远程依赖。

implementation "io.github.liukai2530533:round_circle_imageview:1.0.1"

具体的使用本文上面已经说明了,大家也可以去项目里看看。

作者:newki

链接:/post/7143410101951397919

来源:稀土掘金

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。