您的位置:首页 > 其它

自定义BitmapTransformation完美解决Glide加载圆角或者圆形图片

2017-04-18 15:32 639 查看
当使用Glide加载图片时,如果此时需要使用到圆角图片,我们第一时间会想到自定义ImageView,但是这种方法会报错(记得是类加载异常)。Glide本身提供了transform方法,进行转化。

代码示下:

public class GlideRoundTransform extends BitmapTransformation {

private static float radius = 0f;

public GlideRoundTransform(Context context) {
this(context, 4);
}

public GlideRoundTransform(Context context, int dp) {
super(context);
this.radius = 15f;
}

@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);
}
}


最后我们需要

Glide.with(this).transform(new GlideRoundTransform (this)),就Ok了。

注意:这是设置圆角图片的代码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: