这里用的Glide是4.11.0的
第一种方法:
Glide.with(activity).load(yourUrl).asBitmap().into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
int imageWidth = resource.getWidth();
int imageHeight = resource.getHeight();
int height = ScreenUtils.getScreenWidth() * imageHeight / imageWidth;
ViewGroup.LayoutParams para = imageView.getLayoutParams();
para.height = height;
para.width = ScreenUtils.getScreenWidth();
imageView.setImageBitmap(resource);
}
});
上面这个是主要加载长图或者大图的,这里SimpleTarget《Bitmap》 可以不用传参数直接空构造就好了为啥?
/**
* Constructor for the target that uses {@link Target#SIZE_ORIGINAL} as the target width and
* height.
*/
// Public API.
@SuppressWarnings("WeakerAccess")
public SimpleTarget() {
this(SIZE_ORIGINAL, SIZE_ORIGINAL);
}
glide源码已经设置了初始默认值了,设置了也没有关系
布局:
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
app:layout_constraintTop_toBottomOf="@+id/constraint_head">
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/img_content"
android:adjustViewBounds="true"
android:layout_marginBottom="@dimen/dp50"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.core.widget.NestedScrollView>
仔细看布局,
android:fillViewport="true"
这个方法是nestedscrollview布局不能铺满问题所致
还有一个属性:
android:adjustViewBounds="true"
这个方法是防止有空白出现问题
这个基本可以实现了,但可能图片显示会有问题,因为你不知道会出现什么样的图片,比如,宽高都大于屏幕的大小,这个时候你要进行计算了。这里因为通过glide的几级缓存,已经被压缩过了,有点模糊,之后会有其他的方法,后续补充。
第二种方法:
在后面我找到了一个更好的方法是加载的图片没有上个模糊,并且还要简单一点代码贴上:
val requestOptions = RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) //关键代码,加载原始大小
.format(DecodeFormat.PREFER_RGB_565) //设置为这种格式去掉透明度通道,可以减少内存占有
.placeholder(R.drawable.img_error)
.error(R.drawable.img_error)
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(url)
.into(target)
第三种就是三方库了
https://github.com/davemorrissey/subsampling-scale-image-view
这里没有用过,需要自己去实现了