参考文章
Glide 知识梳理(3) - 自定义transform
glide-transformations
aaa.gif
以前写过一篇自定义ImageView的设置圆角的,但是那个自定义的不可以加载gif动态图的,这次采用transformation的方式来实现,其实思想都差不多的,只是换个套路实现了一下
Glide 版本:4.9.0
总结
1、toTransform 表示网络下载的原图的Bitmap
2、outWidth、outHeight 表示我们ImageView的大小
/**
* @date: 创建时间:2019/10/23
* @author: gaoxiaoxiong
* @descripion:定义Glide的trasformation ,定义圆角
**/
public class FilletTransformation extends BitmapTransformation {
public int radius = 5;
private boolean topLeftRight = false; //上---左右都会圆角
private boolean bottomLeftRight = false;//下----左右都会圆角
public FilletTransformation (int neradius,boolean topRadius,boolean botomRadius){
this.radius = DensityUtil.getInstance().dip2px(neradius);
this.topLeftRight = topRadius;
this.bottomLeftRight = botomRadius;
}
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
Bitmap resultBitmap = pool.get(outWidth,outHeight, getAlphaSafeConfig(toTransform));
BitmapShader bitmapShader = new BitmapShader(toTransform, Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
float scaleMax = 1.0f;
// 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值;
if (outWidth != toTransform.getWidth() || outHeight !=toTransform.getHeight()){
scaleMax = Math.max((float) outWidth / (float)toTransform.getWidth(),(float)outHeight / (float)toTransform.getHeight());
}
Matrix matrix = new Matrix();
matrix.setScale(scaleMax,scaleMax);
bitmapShader.setLocalMatrix(matrix);
Paint mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(bitmapShader);
Canvas canvas = new Canvas(resultBitmap);
RectF drawRectF = new RectF(0,0,outWidth,outHeight);
canvas.drawRoundRect(drawRectF,radius,radius,mPaint);
if (topLeftRight){
//左边底部
canvas.drawRect(0,canvas.getHeight() - radius ,radius,canvas.getHeight(),mPaint);
//右边底部
canvas.drawRect(canvas.getWidth() - radius, canvas.getHeight() - radius,canvas.getWidth(),canvas.getHeight(),mPaint);
}
if (bottomLeftRight){
//左边顶部
canvas.drawRect(0,0,radius,radius,mPaint);
//右边顶部
canvas.drawRect(canvas.getWidth() - radius,0,canvas.getWidth(),radius,mPaint);
}
clear(canvas);
return resultBitmap;
}
@Override
public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
}
// Avoids warnings in M+.
private void clear(Canvas canvas) {
canvas.setBitmap(null);
}
private Bitmap.Config getAlphaSafeConfig(@NonNull Bitmap inBitmap) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Avoid short circuiting the sdk check.
if (Bitmap.Config.RGBA_F16.equals(inBitmap.getConfig())) { // NOPMD
return Bitmap.Config.RGBA_F16;
}
}
return Bitmap.Config.ARGB_8888;
}
}