问题描述
之前写过一篇有关Glide的使用的文章:Android Glide图片加载框架使用过程中遇到的问题总结 ,这篇文章主要针对的是Glide 3.0使用过程中遇到的问题,最近一直在使用Glide 4.0做图片的加载,在最近的项目开发过程中,涉及到了宽度固定,高度自适应的情况(应用场景:流式布局、活动弹窗图等),当时的处理方式是在布局文件中添加如下代码:
<ImageView
android:id="@+id/activity_pic_iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true" />
宽度固定,同时设置android:adjustViewBounds 让其宽高按照原始比例显示。
也可以通过java代码来实现,通过自定义控件实现:
public class MyImageView extends ImageView {
public MyImageView (Context context) {
super(context);
}
public MyImageView (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
Drawable drawable = getDrawable();
if(drawable !=null){
int width = MeasureSpec.getSize(widthMeasureSpec);
//高度根据使得图片的宽度充满屏幕计算而得
int height = (int) Math.ceil((float) width * (float) drawable .getIntrinsicHeight() / (float) drawable .getIntrinsicWidth());
setMeasuredDimension(width, height);
}else{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
然后通过Glide加载网络图片并显示,结果显示处理的图片宽高按照比例正常显示,但是图片显示非常模糊
问题定位
出现上述问题后,如果了解Glide的缓存策略应该知道,Glide 在加载图片的时候,加载的大小会和 ImageView 的大小保持一致。也就是 ImageView 的大小决定了 Glide 加载图片的尺寸。而这里我们的 ImageView 设置的高度是 wrap_content,Glide 就无法准确的加载图片的大小了。具体可以查看:Glide使用及注意的地方
发现问题之后,我们使用Glide应该如何避免这个问题呢?
问题解决
我们知道Glide在加载图片的时候,有多种模式,我们可以通过设置加载原图的方式来显示图片内容:
RequestOptions options = new RequestOptions()
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
通过设置这个属性,配合android:adjustViewBounds,即可实现我们想要的效果。
本文介绍在使用Glide4.0进行图片加载时,遇到的图片显示模糊问题及解决方案。通过分析Glide的缓存策略和加载模式,发现ImageView的wrap_content高度导致图片尺寸加载不准确。通过设置加载原图的方式,结合android:adjustViewBounds属性,实现了图片按比例正常显示且清晰。

2836

被折叠的 条评论
为什么被折叠?



