前面我們通過閱讀ImageView的源碼對ImageView和它的屬性有了更深的認識,這一次我們通過實際應用
來進一步了解他們:
首先我們找一張圖(兩種尺寸750*1334和1242*2208)放到對應(相近)的檔案夾下面,mipamap各檔案夾對應
的手機分辨率:
ldpi 320*240
mdpi 480*320
hdpi 800*480
xhdpi 1280*720
xxhdpi 1920*1080
xxxhdpi 3840×2160
單獨使用src屬性:
布局檔案(固定寬高,友善我們檢視各屬性作用)
顯示效果:
當我們将固定寬高改成wrapcontent時,顯示效果如下:
是不是感覺很奇怪,這并不是我們想要的效果啊?于是我們又去剖析源碼:是不是特别辣眼睛,這并不是我們想要的效果啊?于是我們又去剖析源碼:
代碼一:
final int index = a.getInt(R.styleable.ImageView_scaleType, -1);
if (index >= 0) {
setScaleType(sScaleTypeArray[index]);
}
代碼二:
private void initImageView() {
mMatrix = new Matrix();
mScaleType = ScaleType.FIT_CENTER;
/××省略不相關代碼若幹/
}
于是我們知道了,當mScaleType屬性不設定任何值時,預設為:ScaleType.FIT_CENTER,即按比例進行拉伸,直到視圖的某一條邊完全重合,并将拉伸後的結果顯示在視圖中間,這樣是不是清楚了。
小結一:src屬性隻是提供了資源圖檔的id,并不會對圖檔的顯示效果産生任何影響。
maxWidth和maxHeight屬性:
布局檔案不變:
注意設定:adjustViewBounds = “true”;
顯示效果如下:
是不是又很奇怪,一點作用沒起?于是我們再去看源碼:
* An optional argument to supply a maximum width for this view. Only valid if
* {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a maximum
* of 100 x 100 while preserving the original aspect ratio,
do the following: 1) set * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width * layout params to WRAP_CONTENT.
* Note that this view could be still smaller than 100 x 100 using this approach if the original
* image is small. To set an image to a fixed size, specify that size in the layout params and
* then use {@link #setScaleType(android.widget.ImageView.ScaleType)} to determine how to fit
* the image within the bounds.
@android.view.RemotableViewMethod
public void setMaxWidth(int maxWidth) {
mMaxWidth = maxWidth;
}
注意源碼中标粗的位置:給一張Image設定maxWidth和maxHeight須做以下三步:1)設定adjustViewBounds為true,2)設定 maxHeight和maxWidth的值,3)設定height和width的參數為WRAP_CONTENT于是,我們将width和height的值改為WRAP_CONTENT,顯示效果如下:
這樣就達到了我們想要的效果(預設縮放形式,可使用scaleType設定自己想要的縮放形式)
小結二:maxHeight和maxWidth屬性隻有在adjustViewBounds為true,width和height值為WRAP_CONTENT時起作用,并且它仍有可能小于設定的值,内部已預設的形式進行縮放,可以根據具體情況,設定自己的縮放形式。
scaleType屬性:
1)隻設定scaleType屬性,不設定adjustViewBounds屬性(預設為false)
布局檔案:
設定scaleType為center:不縮放,截取中間部分顯示,如下圖所示:
設定scaleType為centerCrop按比例均勻縮放,直至充滿視圖的寬高,并顯示在視圖的中間,如下圖所示:
設定scaleType為centerInside:當View的寬高>=圖檔的寬高時,圖檔居中顯示原大小反之将原圖按比例縮放至View的寬高居中顯示,如下圖所示:
設定scaleType為fitCenter:按比例進行拉伸,直到視圖的某一條邊完全重合,并将拉伸後的結果顯示在視圖中間如下圖所示:
設定scaleType為fitXY:縮放時X和Y互不影響,即不按比例縮放,如下圖所示:
設定scaleType為fitStart:按原有的縱橫比進行拉伸,直到視圖的某一條邊完全重合,使拉伸結果對其到左部和頂部,如下圖所示:
設定scaleType為fitEnd:按比例進行拉伸,直到視圖的某一條邊完全重合,并将拉伸後的結果顯示在視圖底部,如下圖所示:
設定scaleType為matrix:繪圖時使用圖像矩陣縮放,如下圖所示:
以上就是ImageView的屬性使用具體示例。關于tint屬性我們後面會單獨介紹。