glide設置成圓角圖片 以及解決刷新圖片閃爍的問題

在項目中,我們經常會用到圓角圖片,強大的glide能很簡單通過自定義BitmapTransformation就能實現。

我就隨便網上找了個,然鵝,發現在recyclerview的item裏面,卻刷新時候圖片居然閃動。

在這裏插入圖片描述
後來查找官方文檔

發現在這裏插入圖片描述

對於任何 Transformation 子類,包括 BitmapTransformation,你都必須實現這三個方法,以使得磁盤和內存緩存正確地工作:

equals()
hashCode()
updateDiskCacheKey

網上很多,只是簡單的裁切,而沒有複寫,所以,glide刷新時候會閃動一下。

~~

直接上代碼:

~~

public class GlideRoundTransform extends BitmapTransformation {

        private final float radius;
        private final String ID = "com. bumptech.glide.transformations.FillSpace";
        private final byte[] ID_ByTES= ID.getBytes(CHARSET);

        public GlideRoundTransform(int dp){
           this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
       }

      @Override
      protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight){
          return roundCrop(pool, toTransform);
       }

    private Bitmap roundCrop(BitmapPool pool, Bitmap toTransform) {
        if (toTransform == null) {
            return null;
        }
        Bitmap result = pool.get(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888);
        if (result == null) {
            return Bitmap.createBitmap(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setShader(new BitmapShader(toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        RectF rectF = new RectF(0f, 0f, toTransform.getWidth(), toTransform.getHeight());
       canvas.drawRoundRect(rectF, radius, radius, paint);
       
        return result;
    }


    @Override
    public boolean equals(Object o){
        if (o instanceof GlideRoundTransform){
            GlideRoundTransform other = (GlideRoundTransform) o;
            return radius == other.radius;
        }
        return false;
    }

    @Override
    public int hashCode() {

        return Util.hashCode(ID.hashCode(),
                Util.hashCode(radius));

    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest){
       messageDigest.update(ID_ByTES);
       byte[] radiusData =ByteBuffer.allocate(4).putInt((int) radius).array();messageDigest.update(radiusData);
    }

}

使用

   Glide.with(mContext)
                    .load(url)
                    .apply(new  RequestOptions()
                    .transform( new GlideRoundTransform(4)))
                    .placeholder(placeimg).fallback(placeimg)
                    .error(placeimg)
                    .into(imageView);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章