圖片寬度為控制元件寬度,高度按比例縮放
阿新 • • 發佈:2019-02-04
圖片寬度固定,高度按比例縮放自適應
本身不知道圖片寬度和高度
首先,定義ImageView,在該ImageView中,我們需要設定屬性android:adjustViewBounds="true",他的意思圖片是否保持寬高比。切記的一點是該屬性需要與maxWidth、MaxHeight一起使用,否則單獨使用沒有效果。
- <ImageView
- android:id="@+id/img_list"
- android:layout_width="fill_parent"
-
android:layout_height="wrap_content"
- android:scaleType="centerCrop"
- android:adjustViewBounds="true"
- android:src="@drawable/load_default_img"/>
android:adjustViewBounds="true"必須與MaxHeight一起使用才能有效,所以,我要設定該ImageView的最大高度MaxHeight:
- int screenWidth = getScreenWidth(this); // 獲取螢幕寬度
-
ViewGroup.LayoutParams lp = testImage
- lp.width = screenWidth;
- lp.height = LayoutParams.WRAP_CONTENT;
- testImage.setLayoutParams(lp);
- testImage.setMaxWidth(screenWidth);
- testImage.setMaxHeight(screenWidth * 5); //這裡其實可以根據需求而定,我這裡測試為最大寬度的5倍