在電商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);
}
}