Android進階之路系列:http://blog.csdn.net/column/details/16488.html
我們在android開發過程中可能會遇到一種情況,一個組件需要保持固定的寬高比,但是組件本身大小卻不定。尤其在android屏幕碎片化的情況下,很多時候我們需要讓一個組件寬度與屏幕寬度一致,這樣就無法確定寬度。那麼如何讓控件保持固定寬高比?有幾種方法供大家選擇。
1、自定義view
自定義view,重寫onMeasure或onLayout等相關方法,通過預定的比例計算寬高。下面是簡單示意:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
if (mRatio != 0) {
float height = width / mRatio;
heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) height, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
這種方法不方便的地方是需要自己重新寫一個類。2、ImageView的adjustViewBounds
爲ImageView設置adjustViewBounds,如下:android:adjustViewBounds="true"
這個方法只能用於ImageView
3、百分比佈局
Android提供了Android-percent-support這個庫,支持百分比佈局,包括PercentRelativeLayout和PercentFrameLayout。使用PercentFrameLayout也可以實現一個組件的固定比例顯示,代碼如下:
<android.support.percent.PercentFrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="fitXY"
app:layout_widthPercent="100%"
app:layout_aspectRatio="@fraction/circle_article_aspectRatio"
/>
</android.support.percent.PercentFrameLayout>
需要在res/values下新建一個fraction.xml,代碼如下:<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="circle_article_aspectRatio" type="fraction">133%</item>
</resources>
這樣就實現了寬高4:3的比例。這個方法的好處是不必新建類,但是組件外層需要包裹一個百分比佈局。
4、ConstraintLayout的DimensionRatio
與百分比佈局類似。代碼如下:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:src="@mipmap/bb"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintDimensionRatio="4:3"
/>
</android.support.constraint.ConstraintLayout>
可能產生的幾個情況如下:1、如果組件寬高都設置0dp,組件寬高按比例,且只受父view的約束。如圖
2、如果其中一個設置成了wrap_content或match_parent,比如說寬度,那麼寬度就會是圖片的真實寬度和父view的限制寬度的較小值,而高度會根據寬度和比例計算出來。
這時如果圖片較小,就不會撐滿父View。如圖
3、如果寬高都設置成了wrap_content或match_parent,則比例失效。如圖:
注意:
1、當寬高都設置爲0dp時,app:layout_constraintLeft_toLeftOf="parent"和app:layout_constraintRight_toRightOf="parent"不能省略,否則組件大小爲0。
2、當寬高其中一個或都設置爲wrap_content時,如果去掉app:layout_constraintLeft_toLeftOf="parent"和app:layout_constraintRight_toRightOf="parent"則比例失效。
Android進階之路系列:http://blog.csdn.net/column/details/16488.html