Glide使用CircleImageView,顯示圖片出錯的問題
阿新 • • 發佈:2019-01-09
前言
Glide通過CircleImageView來載入圖片…………是個大坑,很多人估計都遇到過這種情況:當通過Glide來在CircleImageView上載入圖片的時候,第一次顯示的是佔位圖,重新整理一次才是要載入的圖片。現在寫下這篇部落格,記錄下解決方法。
正文
public class GlideCircleImage extends BitmapTransformation {
public GlideCircleImage(Context context) {
super(context);
}
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null)
return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
// TODO this could be acquired from the pool too
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);
return result;
}
@Override
public String getId() {
return getClass().getName();
}
}
相應的,用法:
GlideCircleImage circleImage = new GlideCircleImage(context);
Glide.with(context).load(xxx).transform(circleImage).placeholder(R.drawable.default_avatar).crossFade().into(avatar);