glide设置成圆角图片 以及解决刷新图片闪烁的问题
程序员文章站
2024-03-22 23:43:46
...
在项目中,我们经常会用到圆角图片,强大的glide能很简单通过自定义BitmapTransformation就能实现。
我就随便网上找了个,然鹅,发现在recyclerview的item里面,却刷新时候图片居然闪动。
后来查找官方文档
发现
对于任何 Transformation 子类,包括 BitmapTransformation,你都必须实现这三个方法,以使得磁盘和内存缓存正确地工作:
equals()
hashCode()
updateDiskCacheKey
网上很多,只是简单的裁切,而没有复写,所以,glide刷新时候会闪动一下。
~~
直接上代码:
~~
public class GlideRoundTransform extends BitmapTransformation {
private final float radius;
private final String ID = "com. bumptech.glide.transformations.FillSpace";
private final byte[] ID_ByTES= ID.getBytes(CHARSET);
public GlideRoundTransform(int dp){
this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight){
return roundCrop(pool, toTransform);
}
private Bitmap roundCrop(BitmapPool pool, Bitmap toTransform) {
if (toTransform == null) {
return null;
}
Bitmap result = pool.get(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888);
if (result == null) {
return Bitmap.createBitmap(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setShader(new BitmapShader(toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
RectF rectF = new RectF(0f, 0f, toTransform.getWidth(), toTransform.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
}
@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).putInt((int) radius).array();messageDigest.update(radiusData);
}
}
使用
Glide.with(mContext)
.load(url)
.apply(new RequestOptions()
.transform( new GlideRoundTransform(4)))
.placeholder(placeimg).fallback(placeimg)
.error(placeimg)
.into(imageView);
上一篇: java基础入门-建立可以多客户端链接的ServerSocket
下一篇: JDBC封装