Glide工具类,自适应宽度加载图片。保持图片的长宽比例不变,通过修改imageView的高度来完全显示图片
public class GlideUtils {
/**
* 自适应宽度加载图片。保持图片的长宽比例不变,通过修改imageView的高度来完全显示图片。
*/
public static void loadIntoUseFitWidth(Context context, final String imageUrl, int errorImageId, final ImageView imageView) {
Glide.with(context)
.load(imageUrl)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.listener(new RequestListener<Drawable>() { // 加载监听
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
if (imageView == null) {
return false;
}
if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
}
ViewGroup.LayoutParams params = imageView.getLayoutParams();
int vw = imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight();
float scale = (float) vw / (float) resource.getIntrinsicWidth();
int vh = Math.round(resource.getIntrinsicHeight() * scale);
params.height = vh + imageView.getPaddingTop() + imageView.getPaddingBottom();
imageView.setLayoutParams(params);
return false;
}
})
.error(errorImageId)
.into(imageView);
}
}
网友评论