在电商app中,一般商城详情都会有商品图片详情展示,这些图片需要宽度填充屏幕,高度自适应,
但是ImageView 自带的的scaleType 是无法满足这种需求的,那么有什么方式可以实现呢:
第一种:
使用图片加载框架Glide实现
Glide.with(mContext)
.asBitmap()
.load(imgUrl)
// .override(screenWidth, screenHeight)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
int imageWidth = resource.getWidth();
int imageHeight = resource.getHeight();
//宽度固定,然后根据原始宽高比得到此固定宽度需要的高度
//screenWidth 是屏幕宽度
int height = screenWidth * imageHeight / imageWidth;
ViewGroup.LayoutParams para = mImageView.getLayoutParams();
para.height = height;
para.width = screenWidth;
mImageView.setImageBitmap(resource);
}
});
第二种:(推荐)
我们可以重写ImageView的onMeasure方法,让图片的宽填充屏幕,高自适应
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
Drawable drawable = getDrawable();
if(drawable !=null){
//图片 使用android:layout_width="match_parent",得到的是整个屏幕宽
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);
}
}