Glide載入圓形圖片並且帶白色邊框(絕對實用)
阿新 • • 發佈:2018-12-15
1、建立一個類
/** * 載入圓形頭像帶白色邊框 */ 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、在Activity中實用
Glide.with(this).load("http://05imgmini.eastday.com/mobile/20181013/20181013_da58d8665e2d35cd7c2ad4db1a820288_cover_mwpm_03200403.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);