介绍
图像视图(ImageView)用于在屏幕中显示任何 Drawable 对象,通常用来显示图片。在使用ImageView组件显示图像时,通常需要将要显示的图片放置在res\drawable或者res\mipmap目录中。
XML属性
- background会根据ImageView组件给定的长宽进行拉伸
- src就存放的是原图的大小,不会进行拉伸
setImageBackground
setImageResource
XML属性 | 描述 |
android:adjustViewBounds | 用于设置 ImageView 组件是否调整自己的边界来保持所显示图片的长宽比 |
android:maxHeight | 设置 ImageView 组件的最大高度,需要设置 android:adjustViewBounds 属性值true,否则不起作用 |
android:maxWidth | 设置 ImageView 组件的最大宽度,需要设置 android:adjustViewBounds 属性值为true,否则不起作用 |
android:scaleType | 用于设置所显示的图片如何缩放或移动以适应 ImageView 的大小,其属性值可以是: matrix(使用 matrix 方式进行缩放)、fitXY(对图片横向、纵向独立缩放,使得该图片完全适应于该 ImageView,图片的纵横比可能会改变) fitStart(保持纵横比缩放图片,直到该图片能完全显示在 ImageView 中,缩放完成后该图片放在 ImageView 的左上角) fitCenter(保持纵横比缩放图片,直到该图片能完全显示在 ImageView 中,缩放完成后该图片放在 ImageView 的中间) fitEnd(保持纵横比缩放图片,直到该图片能完全显示在 ImageView 中,缩放完成后该图片放在 ImageView 的右下角) center(把图像放在 ImageView 的中间,但不进行任何缩放) centerCrop(保持纵横比缩放图片,以使得图片能完全覆盖 ImageView)或 centerInside(保持纵横比缩放图片,以使得 ImageView 能完全显示该图片) |
android:src | 用于设置 ImageView 所显示的 Drawable 对象的 ID,例如,设置显示保存在 res/drawable 目录下的名称为 flower.jpg 的图片,可以将属性值设置为 android:src=”@drawable/flower” |
android:tint | 用于为图片着色,其属性值可以是 #rgb、#argb、#rrggbb 或 #aarrggbb 表示的颜色值 |
例子
xml属性测试
如果不设置android:scaleType,等效于centerInside等效于fitCenter
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
android:gravity="center_horizontal">
<ImageView
android:id="@+id/iv_1"
android:layout_width="300dp"
android:layout_height="200dp"
android:background="#FF9900"
android:src="@drawable/bg_aknights"
android:scaleType="fitXY" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fitXY"
android:layout_marginTop="10dp"
android:background="@color/white" />
<ImageView
android:id="@+id/iv_2"
android:layout_width="300dp"
android:layout_height="200dp"
android:background="#FF9900"
android:src="@drawable/bg_aknights"
android:scaleType="centerCrop"
android:layout_below="@+id/iv_1"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="210dp"
android:text="centerCrop"
android:background="@color/white"
/>
<ImageView
android:id="@+id/iv_3"
android:layout_width="300dp"
android:layout_height="200dp"
android:background="#FF9900"
android:src="@drawable/bg_aknights"
android:scaleType="fitCenter"
android:layout_below="@+id/iv_2"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="420dp"
android:text="fitCenter"
android:background="@color/white"
/>
</RelativeLayout>