Glide .centerCrop() 和transform圆角图片不能同时存在解决方法

时间:2022-07-21 10:21:43

问题描述:很多图片是圆角矩形加CenterCrop的效果或者圆形加CenterCrop的效果。稀里糊涂将Glide升级到了4.0.0,发现transform不再可以传多个参数了,之前还可以同时传centerCrop和自己的transform,现在不可以了。Glide有centerCrop()方法,也有transform里传CenterCrop,布局文件scaleType传centerCrop,发现都不能和transform(new GlideRoundTransform())共存。
后来参考overflow解决了,如下:

1.
public class GlideRoundTransformCenterCrop extends CenterCrop {}
之前是继承BitmapTransformation,现在改为直接继承CenterCrop。
2.
重写transform
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform,
int outWidth, int outHeight) {
Bitmap transform = super.transform(pool, toTransform, outWidth, outHeight);
return roundCrop(pool, transform);
}
很明白了,就是先调用super的CenterCrop处理,得到的结果再在自己的roundCrop里处理。
剩下的直接贴了
private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
if (source == null)
return null;
Bitmap result = pool.get(source.getWidth(), source.getHeight(),
Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(source.getWidth(), source.getHeight(),
Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP,
BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {

}