维护老项目真是头秃..
//环境版本
api 'com.github.bumptech.glide:glide:3.7.0'
api 'jp.wasabeef:glide-transformations:2.0.1'
需求是加载动态图片,不限高度,宽度一屏,加圆角,写完发现圆角总是被切的情况
解决代码:
Glide.with(this).load(imgPath).asBitmap()
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, glideAnimation: GlideAnimation<in Bitmap>) {
val para = iv_active.layoutParams
para.height = (iv_active.width.toFloat() / resource.width * resource.height).toInt()
iv_active.layoutParams = para
//加载圆角矩形,transform不能重复多次
Glide.with(this@BrandDetailActivity)
.load(imgPath)
.placeholder(R.drawable.ic_launcher)
.transform(CenterCrop(this@BrandDetailActivity), GlideRoundTransform(this@BrandDetailActivity, 8))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.crossFade()
.dontAnimate()
.into(iv_active)
}
})
最终效果
public class GlideRoundTransform extends BitmapTransformation {
private static float radius = 0f;
/**
* 构造函数 默认圆角半径 4dp
*
* @param context Context
*/
public GlideRoundTransform(Context context) {
this(context, 4);
}
/**
* 构造函数
*
* @param context Context
* @param dp 圆角半径
*/
public GlideRoundTransform(Context context, int dp) {
super(context);
radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return roundCrop(pool, toTransform);
}
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 String getId() {
return getClass().getName() + Math.round(radius);
}
}