ImageView
是 [Android] 中最常用的控件之一,而在使用ImageView
时,必不可少的会使用到它的scaleType
属性。该属性指定了你想让ImageView
如何显示图片,包括是否进行缩放、等比缩放、缩放后展示位置等。Android 提供了八种scaleType
的属性值,每种都对应了一种展示方式,下面就对每一种scaleType
属性值进行图文解释。
首先,这张图是1920*1080,无论长宽都比测试所用的ImageView
大。
原图篇

这个是用于测试的ImageView布局:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent">
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/ivTest"
android:layout_width="match_parent"
android:layout_height="300dip"
android:background="@color/colorPrimary" />
</FrameLayout>
可以看到ImageView是正方形的,其背景色为橙色,父布局设置其背景色为蓝色,这样可以很容易看到各个控件的大小。在手机上这个布局看起来是这个样子的,橙色空间就是ImageView:

八个ScaleType
,其实可以分为三个类型:
- 以
FIT_
开头的4种,它们的共同点是都会对图片进行缩放; - 以
CENTER_
开头的3种,它们的共同点是居中显示,图片的中心点会与ImageView
的中心点重叠; -
ScaleType.MATRIX
,这种就直接翻到最后看内容吧;
ScaleType.FIT_CENTER 默认
该模式是ImageView
的默认模式,如果没有设置ScaleType
时,将采用这种模式展示图片。在该模式下,图片会被等比缩放到能够填充控件大小,并居中展示:

这里例子里因为图片宽大于高,于是被缩放到控件大小并居中展示,上下会留白。如果图片的高大于宽,那么居中显示就会在左右留白。
ScaleType.FIT_START
图片等比缩放到控件大小,并放置在控件的上边或左边展示。如图所示,此模式下会在ImageView
的下半部分留白,如果图片高度大于宽,那么就会在ImageView
的右半部份留白。

ScaleType.FIT_END
图片等比缩放到控件大小,并放置在控件的下边或右边展示。如图所示,此模式下会在ImageView
的上半部分留白,如果图片高度大于宽,那么就会在ImageView
的左半部分留白。

ScaleType.FIT_XY
图片缩放到控件大小,完全填充控件大小展示。注意,此模式不是等比缩放。这个模式理解也是最简单的,如图:

ScaleType.CENTER
不使用缩放,ImageView
会展示图片的中心部分,即图片的中心点和ImageView
的中心点重叠,如图。如果图片的大小小于控件的宽高,那么图片会被居中显示。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent">
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/ivTest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@color/colorPrimary"
android:scaleType="center"
android:src="@mipmap/test" />
</FrameLayout>

ScaleType.CENTER_CROP
图片会被等比缩放直到完全填充整个ImageView
,并居中显示。该模式也是最常用的模式了。如图可以看到,图片的高度是能完全展示出来的:

ScaleType.CENTER_INSIDE
使用此模式以完全展示图片的内容为目的。图片将被等比缩放到能够完整展示在ImageView
中并居中,如果图片大小小于控件大小,那么就直接居中展示该图片:

ScaleType.MATRIX
在这八种ScaleType
中,该模式需要与ImageView.setImageMatrix(Matrix matrix)
配合使用,指定一个矩阵用于图片如何展示。前面的7种模式都是通过ImageView
在内部生成了相应的变换矩阵,等于是提供了该模式。
注意顺序不要搞错,否则会出现问题的。下面看一下代码:
imageView.setScaleType(ImageView.ScaleType.MATRIX); //设置为矩阵模式
Matrix matrix = new Matrix(); //创建一个单位矩阵
matrix.setTranslate(100, 100); //平移x和y各100单位
matrix.preRotate(30); //顺时针旋转30度
imageView.setImageMatrix(matrix); //设置并应用矩阵
每行代码都有注释,其展示的效果如下图显示

最后自己找张图片练练手试试

网友评论