1. 程式人生 > >Glide4.7.1 圓角與centerCrop衝突問題

Glide4.7.1 圓角與centerCrop衝突問題

問題:在glide配置中使用options.transforms(new GlideRoundedCornersTransform(context,5));來實現圓角以及centerCrop效果時,重新整理介面會出現閃爍
解決方法:由於glide預設採用了centerCrop方式顯示圖片,所以基本不需要再次設定,而圓角採用自定義控制元件的方式就可以實現其效果並不會出現閃爍問題

當然如果不介意可以使用下面方法:

public class GlideRoundTransform extends CenterCrop {

    private static float radius = 10f;

    public GlideRoundTransform(Context context) {
        this(context, 10);
    }

    public GlideRoundTransform(Context context, int dp) {
        super();
        this.radius = UnitConversionUtil.dip2px(context, dp);
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        //glide4.0+
        Bitmap transform = super.transform(pool, toTransform, outWidth, outHeight);
        return roundCrop(pool, transform);
        //glide3.0
        //return roundCrop(pool, toTransform);
    }

    private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;

        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        }

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

    }
}