Glide4加载图片显示圆角和显示头像圆形图片

2020-01-20  本文已影响0人  执念蓝枫

https://blog.csdn.net/qq_27706837/article/details/87978432

关键工具类

public class CenterCropRoundCornerTransform extends CenterCrop {
    private static float radius = 0f;
 
    public CenterCropRoundCornerTransform(int px) {
        this.radius = px;
    }
 
    @Override
    protected Bitmap transform(BitmapPool pool, 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_4444);
        if (result == null) {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_4444);
        }
 
        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 = bitmapTransform(new CenterCropRoundCornerTransform(radius));
        GlideApp.with(context)
                .load(url)
                .apply(options)
                .placeholder(R.drawable.loading)
                .error(R.drawable.loading)
                .into(view)

上一篇下一篇

猜你喜欢

热点阅读