Glide等比缩放图片问题总结

前言

等比例缩放图片在聊天列表中比较常见,而不是显示固定宽高的图片。最近对IM项目迁移到Androidx时,顺便升级了glide,发现glide等比例缩放图片出现bug(自定义ImageViewTarget实现图片缩放),第一次能正常加载,第二次无法正常等比例缩放。原来项目是使用glide 3.7.0,现在是使用gilde 4.11.0 (4.10.0开始支持AndroidX)

解决方案

不同版本glide,ImageViewTarget使用差异如下:

glide 3.6.0

public class GlideRatioScaleTransForm extends ImageViewTarget<Bitmap> {

    private ImageView target;

    public GlideRatioScaleTransForm(ImageView target) {
        super(target);
        this.target = target;
    }

    @Override
    protected void setResource(Bitmap resource) {
        view.setImageBitmap(resource);

        int width = resource.getWidth();
        int height = resource.getHeight();

        //获取imageView的宽
        int imageViewWidth = target.getWidth();

        //计算缩放比例
        float sy = (float) (imageViewWidth * 0.2) / (float) (width * 0.2);

        //计算图片等比例放大后的高
        int imageViewHeight = (int) (height * sy);
        ViewGroup.LayoutParams params = target.getLayoutParams();
        params.height = imageViewHeight;
        target.setLayoutParams(params);
    }
}

glide 4.11.0

public class GlideRatioScaleTransForm extends ImageViewTarget<Bitmap> {

    public GlideRatioScaleTransForm(ImageView target) {
        super(target);
    }

    @Override
    protected void setResource(@Nullable Bitmap resource) {
        if (resource == null) {
            return;
        }
        view.setImageBitmap(resource);
        int width = resource.getWidth();
        int height = resource.getHeight();

        //获取imageView的宽
        int imageViewWidth = view.getWidth();
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (imageViewWidth <=0){//修复等比例缩放bug
            imageViewWidth = params.width;
        }
        //计算缩放比例
        float sy = (float) (imageViewWidth * 0.2) / (float) (width * 0.2);
        //计算图片等比例放大后的高
        int imageViewHeight = (int) (height * sy);
        params.height = imageViewHeight;
        view.setLayoutParams(params);
    }


}

使用

 <ImageView
        android:id="@+id/iv_img"
          android:layout_width="110dp"
          android:layout_height="110dp"
          />
//3.7.0
Glide.with(mContext)
                  .load(HttpConstant.SWIM_CHAT_BASE_URL + imageMessageBody.getUrl())
                  .asBitmap()
                  .placeholder(R.color.white)
                  .thumbnail(0.5f)//缩略图
                  .diskCacheStrategy(DiskCacheStrategy.ALL)
                  .into(new GlideRatioScaleTransForm(iv_img));

 //4.11.0,asBitmap() 需要设置在 load(url)之前
 Glide.with(mContext)
         .asBitmap()
            .load(HttpConstant.SWIM_CHAT_BASE_URL + imageMessageBody.getUrl())
            .placeholder(R.color.white)
            .thumbnail(0.5f)//缩略图
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .into(new GlideRatioScaleTransForm(iv_img));

猜你喜欢

转载自blog.csdn.net/u011082160/article/details/105834015