茴香豆的茴有几种写法?这不需探究,也没有意义。本文探究的是圆角图片有几种实现方案,这应该是有意义的。
方案一:色彩混合+绘制Path
第一种方案是利用色彩混合PorterDuffXfermode
绘制Path,其原理是根据数学公式对目标对象(原始图片)和源对象(圆角矩形)进行混合显示,混合模式PorterDuff.Mode
共有18种,需要能够看懂这18种混合模式的数学公式的含义。
我们要使用的是PorterDuff.Mode.DST_IN
,其实只要看懂了PorterDuff.Mode.DST_IN
的数学公式的含义,其他17种的含义也就很好理解了。PorterDuff.Mode.DST_IN
语言解释是这样的:两者相交的地方绘制目标对象,不相交的地方不进行绘制,并且相交处的效果会受到源对象对应地方透明度的影响。这18种模式在Android矢量图(二)--VectorDrawable所有属性全解析这篇文章中介绍的很清晰。
下面看下RRImageOne.java
的源码:
public class RRImageOne extends AppCompatImageView {
long time = System.currentTimeMillis();
private int cornerRadius; // Set the radius of rounded corners uniformly, priority is higher than setting the radius of each corner separately.
private int cornerTopLeftRadius, cornerTopRightRadius, cornerBottomLeftRadius, cornerBottomRightRadius;
private float[] srcRadii = new float[8];
private RectF srcRectF = new RectF();
private Paint paint = new Paint();;
private Path path;
public RRImageOne(Context context) {
this(context, null);
}
public RRImageOne(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RRImageOne(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RRImageOne, 0, 0);
cornerRadius = ta.getDimensionPixelSize(R.styleable.RRImageOne_corner_r, cornerRadius);
cornerTopLeftRadius = ta.getDimensionPixelSize(R.styleable.RRImageOne_corner_top_left_r, cornerTopLeftRadius);
cornerTopRightRadius = ta.getDimensionPixelSize(R.styleable.RRImageOne_corner_top_right_r, cornerTopRightRadius);
cornerBottomLeftRadius = ta.getDimensionPixelSize(R.styleable.RRImageOne_corner_bottom_left_r, cornerBottomLeftRadius);
cornerBottomRightRadius = ta.getDimensionPixelSize(R.styleable.RRImageOne_corner_bottom_right_r, cornerBottomRightRadius);
ta.recycle();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
//init radii
if (cornerRadius > 0) {
for (int i = 0; i < srcRadii.length; i++) {
srcRadii[i] = cornerRadius;
}
} else {
srcRadii[0] = srcRadii[1] = cornerTopLeftRadius;
srcRadii[2] = srcRadii[3] = cornerTopRightRadius;
srcRadii[4] = srcRadii[5] = cornerBottomRightRadius;
srcRadii[6] = srcRadii[7] = cornerBottomLeftRadius;
}
//change bg
Drawable bg = getBackground();
if (bg instanceof ColorDrawable) {
GradientDrawable sd = new GradientDrawable();
sd.setCornerRadii(srcRadii);
sd.setColor(((ColorDrawable) bg).getColor());
setBackgroundDrawable(sd);
}
setScaleType(ScaleType.CENTER_CROP);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
srcRectF.set(0, 0, w, h);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.saveLayer(srcRectF, null, Canvas.ALL_SAVE_FLAG);//or bg will have black edge
super.onDraw(canvas);
path = new Path();
path.addRoundRect(srcRectF, srcRadii, Path.Direction.CCW);
canvas.drawPath(path, paint);
canvas.restore();
Log.d("zzh", "one: time consume="+(System.currentTimeMillis()-time));
}
}
Activity的页面布局源码:
自定义的style:
效果展示:
方案二:Matrix+Shader+画布剪切
第二种方案使用到了两个知识点,一个知识点是调节矩阵Matrix并赋给Shader,再把Shader赋给Paint,最后利用Paint和Canvas绘制原来的Bitmap,在此之前可以绘制背景,在此之后可以绘制边框,这需要对矩阵Matrix、Shader、线性代数运算等有所了解。另一个知识点是Canvas的剪切,根据矩形区域mDrawableRect和八个半径数组clipRadii构造一个Path path,利用这个path对画布进行剪切,这里只需要三行代码:
Path path = new Path();
path.addRoundRect(mDrawableRect, clipRadii, Path.Direction.CCW);
canvas.clipPath(path);
RRImageTwo.java
源码:
public class RRImageTwo extends AppCompatImageView {
long time = System.currentTimeMillis();
private final RectF mDrawableRect = new RectF();
private float[] clipRadii = new float[8];
private int cornerRadius; // Set the radius of rounded corners uniformly, priority is higher than setting the radius of each corner separately.
private int cornerTopLeftRadius, cornerTopRightRadius, cornerBottomLeftRadius, cornerBottomRightRadius;
private final Matrix mShaderMatrix = new Matrix();
private final Paint mBitmapPaint = new Paint();
private final Paint mBgPaint = new Paint();
private int mBgColor = Color.TRANSPARENT;
private Bitmap mBitmap;
private BitmapShader mBitmapShader;
private int mBitmapWidth;
private int mBitmapHeight;
private float mDrawableRadius;
private boolean mReady;
private boolean mSetupPending;
public RRImageTwo(Context context) {
this(context, null);
}
public RRImageTwo(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RRImageTwo(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RRImageTwo, defStyle, 0);
mBgColor = ta.getColor(R.styleable.RRImageTwo_civ_fill_color, mBgColor);
cornerRadius = ta.getDimensionPixelSize(R.styleable.RRImageTwo_civ_corner_r, cornerRadius);
cornerTopLeftRadius = ta.getDimensionPixelSize(R.styleable.RRImageTwo_civ_corner_top_left_r, cornerTopLeftRadius);
cornerTopRightRadius = ta.getDimensionPixelSize(R.styleable.RRImageTwo_civ_corner_top_right_r, cornerTopRightRadius);
cornerBottomLeftRadius = ta.getDimensionPixelSize(R.styleable.RRImageTwo_civ_corner_bottom_left_r, cornerBottomLeftRadius);
cornerBottomRightRadius = ta.getDimensionPixelSize(R.styleable.RRImageTwo_civ_corner_bottom_right_r, cornerBottomRightRadius);
ta.recycle();
// setLayerType(View.LAYER_TYPE_SOFTWARE, null);
init();
}
private void init() {
if (cornerRadius > 0) {
for (int i = 0; i < clipRadii.length; i++) {
clipRadii[i] = cornerRadius;
}
} else {
clipRadii[0] = clipRadii[1] = cornerTopLeftRadius;
clipRadii[2] = clipRadii[3] = cornerTopRightRadius;
clipRadii[4] = clipRadii[5] = cornerBottomRightRadius;
clipRadii[6] = clipRadii[7] = cornerBottomLeftRadius;
}
mReady = true;
if (mSetupPending) {
setup();
mSetupPending = false;
}
}
@Override
public void setAdjustViewBounds(boolean adjustViewBounds) {
if (adjustViewBounds) {
throw new IllegalArgumentException("adjustViewBounds not supported.");
}
}
@Override
protected void onDraw(Canvas canvas) {
canvas.saveLayer(mDrawableRect, null, Canvas.ALL_SAVE_FLAG);
// canvas.save();
Path path = new Path();
path.addRoundRect(mDrawableRect, clipRadii, Path.Direction.CCW);
canvas.clipPath(path);
drawBg(canvas);
drawBitmap(canvas);
drawBorder(canvas);
canvas.restore();
Log.d("zzh", "two: time consume="+(System.currentTimeMillis()-time));
}
void drawBg(Canvas canvas) {
if (mBgColor != Color.TRANSPARENT) {
float largeEdge = Math.max(getWidth(), getHeight());
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, largeEdge, mBgPaint);
}
}
void drawBitmap(Canvas canvas) {
if (mBitmap != null) {
float largeEdge = Math.max(getWidth(), getHeight());
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, largeEdge, mBitmapPaint);
}
}
void drawBorder(Canvas canvas) {
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Log.d("zzh", "onSizeChanged: mBgPaint=" + mBgPaint);
setup();
}
private void setup() {
Log.d("zzh", "setup: mBgPaint="+mBgPaint);
if (mBgPaint != null) {//这里会报空指针crash,想不明白,请大神留言告知
mBgPaint.setStyle(Paint.Style.FILL);
mBgPaint.setAntiAlias(true);
mBgPaint.setColor(mBgColor);
}
if (!mReady) {
mSetupPending = true;
return;
}
if (getWidth() == 0 && getHeight() == 0) {
return;
}
mDrawableRect.set(0, 0, getWidth(), getHeight());
mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f);
if (mBitmap != null) {
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
updateShaderMatrix();
}
invalidate();
}
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;
}
Log.d("zzh", "mBitmapWidth="+mBitmapWidth+ " mBitmapHeight="+mBitmapHeight+ " drawableWidth=" + mDrawableRect.width() + " drawableHeight" + mDrawableRect.height() + " scale="+scale);
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mDrawableRect.left, (int) (dy + 0.5f) + mDrawableRect.top);
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
mBitmap = bm;
setup();
Log.d("zzh", "setImageBitmap: ");
}
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
mBitmap = getBitmapFromDrawable(drawable);
setup();
Log.d("zzh", "setImageDrawable: ");
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
Log.d("zzh", "setImageResource: ");
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
mBitmap = uri != null ? getBitmapFromDrawable(getDrawable()) : null;
setup();
Log.d("zzh", "setImageURI: ");
}
private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
private static final int COLORDRAWABLE_DIMENSION = 2;
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;
}
}
}
页面布局代码:
自定义的style:
最终效果:
方案三:ViewOutlineProvider
第三种方案是利用ViewOutlineProvider
,这种方案貌似只能实现统一的圆角半径,四个单一的圆角半径貌似做不到。代码使用kotlin编写,源码如下:RRImageThree.kt
:
class RRImageThree @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatImageView(context, attrs, defStyleAttr) {
var cornerRadius = 0f
internal var time = System.currentTimeMillis()
init {
clipToOutline = true
val ta = context.obtainStyledAttributes(attrs, R.styleable.RRImageThree, defStyleAttr, 0)
cornerRadius = ta.getDimensionPixelSize(R.styleable.RRImageThree_c_corner_r, cornerRadius.toInt()).toFloat()
scaleType = ScaleType.CENTER_CROP
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
var outlineProvider: ViewOutlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View?, outline: Outline?) {
outline?.setRoundRect(Rect(0, 0, w, h), cornerRadius)
}
}
this.outlineProvider = outlineProvider
// invalidateOutline()
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
Log.d("zzh", "three: time consume=" + (System.currentTimeMillis() - time))
}
}
样式style:
布局源码:
最终效果图:
比较
最后比较了三种方案的时间性能:
zzh: one: time consume=296
zzh: one: time consume=294
zzh: one: time consume=294
zzh: one: time consume=287
zzh: two: time consume=286
zzh: two: time consume=285
zzh: two: time consume=285
zzh: three: time consume=283
zzh: three: time consume=284
zzh: three: time consume=284
可以看到时间差别不是很大。
如果还有其他方案,请留言,文章会随时更新。