adjustViewBounds 属性使用
问题产生
- 问题描述
当ScrollView
包含一张尺寸过大的图片时,上方自动添加了一大块空白
- 布局文件
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="@mipmap/img_test" />
</ScrollView>
-
异常的效果图
问题解决
ImageView
添加一条属性android:adjustViewBounds="true"
- 修改后布局
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_gravity="center_horizontal"
android:src="@mipmap/img_test" />
</ScrollView>
官方文档
ImageView
官方 API 地址 https://developer.android.com/reference/android/widget/ImageView.html
- setAdjustViewBounds 的API
- android:adjustViewBounds 的API
可以看到上面两块都只讲了一句话
Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.
google
翻译的结果就是
如果您希望ImageView调整边界以保留其可绘制的高宽比,请将其设置为true。
- setMaxWidth 的API
valid 的翻译是 有效
上图红框里面的意思是 setMaxWidth
这个属性只有在 adjustViewBounds
属性是 true 时有效。
- 网上的流传
ImageView的android:adjustViewBounds属性为是否保持原图的长宽比,单独设置不起作用,需要配合maxWidth或maxHeight一起使用。
这句话应该把依赖关系搞反了,maxWidth
的属性依赖于adjustViewBounds
。
而adjustViewBounds
完全可以单独设置,而且有效果。