Glide使用CircleImageView,显示图片出错的问题

  • 前言
  • 正文

前言

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);

你可能感兴趣的:(开发学习随笔)