Glide4.0与centerCrop冲突问题(同时解决刷新闪烁)方案
也许大家会遇到使用加载图片,需要圆角与centerCrop裁剪图片,但是经过常规设置centerCrop,然后再设置圆角,发现实际运行是不生效的,没有圆角,具体的原因可以谷歌下。
下面的解决也是网上千律一篇的解决方案,不过大家在拿来就用的时候,可能没有注意到或者遇到刷新闪烁问题,就需要注意了,因为网上方法不全导致的!
刷新加载Glide 的时候图片会闪动一下,网上提供的各种解决Glide 加载图片出现闪动可能有效,可能没效果,终在下面方法
在此主要解决闪烁问题
大家可以仔细看下,下面方法比网上多了三个方法
- equals()
- hashCode()
- updateDiskCacheKey
/**
* 实现圆角与centerCrop加载实现
*
*/
public class GlideRoundTransform extends BitmapTransformation {
private static final String ID = "com.bumptech.glide.transformations.GlideRoundTransform";
private static final byte[] ID_BYTES = ID.getBytes(Charset.forName("UTF-8"));
private float radius = 0f;
public GlideRoundTransform(Context context) {
this(context, 5);
}
public GlideRoundTransform(Context context, int dp) {
super();
this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
Bitmap bitmap = TransformationUtils.centerCrop(pool, toTransform, outWidth, outHeight);
return roundCrop(pool, bitmap);
}
private 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;
}
public String getId() {
return getClass().getName() + Math.round(radius);
}
//下面三个方法需要实现,不然会出现刷新闪烁
@Override
public boolean equals(Object o) {
if (o instanceof GlideRoundTransform) {
GlideRoundTransform other = (GlideRoundTransform) o;
return radius == other.radius;
}
return false;
}
@Override
public int hashCode() {
return Util.hashCode(ID.hashCode(), Util.hashCode(radius));
}
@Override
public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
messageDigest.update(ID_BYTES);
byte[] radiusData = ByteBuffer.allocate(4).putFloat(radius).array();
messageDigest.update(radiusData);
}
}
这三个方法就是解决闪烁
实际官网给的很清楚,大家可以进行查阅
Transformations:
官网原文解决方案:http://bumptech.github.io/glide/doc/transformations.html
使用:
例如:
GlideApp.with(context)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(placeErrorId)
.error(placeErrorId)
.transform(new GlideRoundTransform(context, roundingRadius))
.into(imageView);