public class RatioImageView extends ImageView { public RatioImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override PRotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Drawable drawable = getDrawable(); if (drawable != null) { // 因為高有問題,所以我們修改這高,讓它按比例算出這個高 int picRealHeight = drawable.getMinimumHeight(); // 獲取圖片真實的高 int picRealWidth = drawable.getMinimumWidth(); // 獲取圖片真實的寬 float scale = (float) picRealHeight / picRealWidth; // 計算圖片高和寬的比例 int width = MeasureSpec.getSize(widthMeasureSpec); // 獲取測量規格 int height = (int) (width * scale); // 按比例計算高度 heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); // 創建測量規格 } super.onMeasure(widthMeasureSpec, heightMeasureSpec); }}了解ImageView的幾個概念
① 前景src
src屬性默認會保持圖片比例不變。
② ImageView的高度
默認采用圖片真實的高。
③ 對于ImageView來說
onMeasure用來測量前景src的寬高尺寸;
onLayout不起作用,其父親為空實現;
④ 為何這么做就好了呢?
ImageView的高度設置為wrap_content,則ImageView的高度就是原始圖片的高度,
而前景src要進行等比例的縮小,顯示效果就是圖片前景高度和ImagView高度不匹配,
將ImageView高度在onMeasure里設置為前景src高度,此時ImageView和前景src高度一致;
⑤ onMeasure作用是啥?
設置ImageView的size和measureSpec:ImageView尺寸和測量規格;
此時ImageView自身獲取到其自身的信息,自身調用onDraw方法;
onMeasure由其父容器的measure調用,為其傳遞尺寸信息;
在ImageView的onMeasure方法里,ImageView可以決定自己的尺寸信息是否需要修改,
如果不需要修改,就采取父容器傳遞過來的尺寸信息。
要求ImageView的前景src和ImageView的高度一致;
要求美工切圖要統一比例,我們對圖片高度不控制,完全由圖片寬度和目標圖片寬度的scale決定。
除了自定義ImageView手動設置ImagaView的高度之外,還可以利用ImageView自帶的一個屬性在xml中聲明,自動設置ImageView的前景和ImagaView的高度自適應:

<ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:background="#6000" android:src="@drawable/sp" /> <View android:layout_width="match_parent" android:layout_height="30dp" /> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#6000" android:scaleType="fitStart" android:src="@drawable/sp" />第一張ImageView高度自適應第二張前景和ImageView的寬度不匹配,之所以出現這種情況是因為,為了保證前景(圖片)的寬高比例不變,對圖片寬度和高度等比例縮放到的最大程度。
新聞熱點
疑難解答