glide 设置圆角的时候会导致ImageView的scaleType
属性无效?导致图片变形?
为什么呢,其实是因为重复调用了transform
方法导致的,
比如new CenterCrop(mContext)
或者是new RequestOptions().centerCrop()
public class CenterCrop extends BitmapTransformation {
....
// Bitmap doesn't implement equals, so == and .equals are equivalent here.
@SuppressWarnings("PMD.CompareObjectsWithEquals")
@Override
protected Bitmap transform(
@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
return TransformationUtils.centerCrop(pool, toTransform, outWidth, outHeight);
}
}
public RequestOptions centerCrop() {
return transform(DownsampleStrategy.CENTER_OUTSIDE, new CenterCrop());
}
可以看到都有调用transform
方法的,
再看一种写法
new RequestOptions().centerCrop().transform(...);
很明显重复了,centerCrop
内部已经调用了transform
方法,然后后面又跟了一个transform
。
自定义一个类去继承BitmapTransformation
:
/**
* Created by yechaoa on 2018/9/10.
* Describe : glide 圆角
*/
public class GlideRoundTransform extends BitmapTransformation {
private static float radius = 0f;
public GlideRoundTransform(int dp) {
super();
radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
Bitmap bitmap = TransformationUtils.centerCrop(pool, toTransform, outWidth, outHeight);
return roundCrop(pool, bitmap);
}
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);
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 void updateDiskCacheKey(MessageDigest messageDigest) {
}
}
参数直接传圆角的度数就行
RequestOptions options =new RequestOptions().transform(new GlideRoundTransform(5));
Glide.with(mContext).load(...).apply(options).into(...);