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

来源:互联网 发布:java新手入门教程视频 编辑:程序博客网 时间:2024/05/20 00:12

当使用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了。
注意:这是设置圆角图片的代码。

1 0