1. 程式人生 > >圖片寬度為控制元件寬度,高度按比例縮放

圖片寬度為控制元件寬度,高度按比例縮放

圖片寬度固定,高度按比例縮放自適應

本身不知道圖片寬度和高度

 首先,定義ImageView,在該ImageView中,我們需要設定屬性android:adjustViewBounds="true",他的意思圖片是否保持寬高比。切記的一點是該屬性需要與maxWidth、MaxHeight一起使用,否則單獨使用沒有效果。 

  1. <ImageView
  2.        android:id="@+id/img_list"
  3.        android:layout_width="fill_parent"
  4.        android:layout_height="wrap_content"
  5.        android:scaleType="centerCrop"
  6.        android:adjustViewBounds="true"
  7.        android:src="@drawable/load_default_img"/>

android:adjustViewBounds="true"必須與MaxHeight一起使用才能有效,所以,我要設定該ImageView的最大高度MaxHeight:
  1. int screenWidth = getScreenWidth(this); // 獲取螢幕寬度  
  2. ViewGroup.LayoutParams lp = testImage
    .getLayoutParams();  
  3. lp.width = screenWidth;  
  4. lp.height = LayoutParams.WRAP_CONTENT;  
  5. testImage.setLayoutParams(lp);  
  6. testImage.setMaxWidth(screenWidth);  
  7. testImage.setMaxHeight(screenWidth * 5); //這裡其實可以根據需求而定,我這裡測試為最大寬度的5倍