1、前言
有时候,我们在应用中加载图片时并不知道图片确切的宽高数值,但是需要保持宽高比,比如我就遇到这样的设计:图片的宽度填满屏幕,宽高比例为16:9,高度根据这个比例自适应。这样加载出来的图片就形同一张卡片。由于不同手机的屏幕宽度不一样,所以图片宽高无法提前在布局中确定,但好在我们还是可以在代码中动态实现的,现在我们就来看看吧。
2、UI布局
为了便于比较,我在布局中放置了两个ImageView,它们除了id以外,其它的属性都一样。一个正常加载图片,两一个则保持16:9的宽高比。
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.lindroid.scaleimageview.SecondActivity">
android:layout_marginTop="10dp"
android:gravity="center"
android:text="普通加载"
android:layout_width="match_parent