Glide加载圆形图片并且带白色边框

1、创建一个类此类是重写Glide中的样式进行更改

   

implementation 'com.github.bumptech.glide:glide:4.0.0-RC1'
/**
 * 加载圆形头像带白色边框
 */
public class GlideCircleWithBorder extends BitmapTransformation {
    private Paint mBorderPaint;
    private float mBorderWidth;
 
    public GlideCircleWithBorder(Context context) {
        super(context);
    }
 
    public GlideCircleWithBorder(Context context, int borderWidth, int borderColor) {
        super(context);
        mBorderWidth = Resources.getSystem().getDisplayMetrics().density * borderWidth;
 
        mBorderPaint = new Paint();
        mBorderPaint.setDither(true);
        mBorderPaint.setAntiAlias(true);
        mBorderPaint.setColor(borderColor);
        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setStrokeWidth(mBorderWidth);
    }
 
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return circleCrop(pool, toTransform);
    }
 
    private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
        if (source == null) {
            return null;
        }
        int size = (int) (Math.min(source.getWidth(), source.getHeight()) - (mBorderWidth / 2));
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;
        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }
        //创建画笔 画布 手动描绘边框
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        if (mBorderPaint != null) {
            float borderRadius = r - mBorderWidth / 2;
            canvas.drawCircle(r, r, borderRadius, mBorderPaint);
        }
        return result;
    }
 
    @Override
    public void updateDiskCacheKey(MessageDigest messageDigest) {
 
    }
}

2 使用

Glide.with(this).load("https://ws1.sinaimg.cn/large/0065oQSqgy1fwyf0wr8hhj30ie0nhq6p.jpg")
                                 .apply(new RequestOptions().error(this.getResources().getDrawable(R.mipmap.piccirclegreen))
                                 .placeholder(R.mipmap.ic_launcher).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL)
                                 .transform(new GlideCircleWithBorder(this, 3, Color.parseColor("#ccffffff"))))
                                 .into(image);

 

你可能感兴趣的:(Glide加载圆形图片并且带白色边框)