做Android开发的童靴们肯定对系统自带的控件使用的都非常熟悉,比如Button、TextView、ImageView等。如果你问我具体使用,我会给说:拿ImageView来说吧,首先创建一个新的项目,在项目布局文件中应用ImageView控件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#bbaacc" >
<ImageView
android:src="@drawable/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#aabbcc" />
</LinearLayout>
上边布局文件为了便于查看各种属性效果,故意加了两个背景颜色,这对我们今天的源码分析影响不大。接着运行一下代码,效果图如下:
恩,不错,运行结果正如所愿,屏幕上显示的正是我们设置的图片,这时候心中不由欣喜ImageView的使用就是这样简单,so easy嘛!呵呵,如果真是这么想那就大错特错了,上边的示例仅仅是在布局文件中使用了ImageView的src,layout_width和layout_height这三个属性罢了,它其他的重要属性我们还没有用到,今天这篇文章就是主要结合源码讲解ImageView的另一个重要的属性------ScaleType,其他的一些属性等将来需要的话再做详细解说。好了,现在正式进入主题。
ScaleType属性主要是用来定义图片(Bitmap)如何在ImageView中展示的,姑且就认为是展示吧,系统给我们提供了8种可选属性:matrix、fitXY、fitStart、fitCenter、fitEnd、center、centerCrop和centerInside。每一种属性对应的展示效果是不一样的,下面我们先来做一个实验来说明每一种属性的显示效果,我从之前的项目中挑选了两张图片,一张图片的实际尺寸是720*1152,另一张是我把第一张图翻转放缩得到的,它的实际尺寸是96*60,之所以采用两张图片是为了便于对比和观察结果,原图片如下:
OK,测试图片准备好了,接下来我们在布局文件中分别使用ScaleType的每一个属性值,我们开始写布局文件,内容如下:
<?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="match_parent"
android:background="#bbccaa" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="图片尺寸的宽和高都远远大于ImageView的尺寸" />
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="300px"
android:layout_height="300px"
android:background="#aabbcc"
android:scaleType="matrix"
android:src="@drawable/test" />
<ImageView
android:layout_width="300px"
android:layout_height="300px"
android:layout_marginLeft="10dp"
android:background="#aabbcc"
android:scaleType="fitXY"
android:src="@drawable/test" />
<ImageView
android:layout_width="300px"
android:layout_height="300px"
android:layout_marginLeft="10dp"
android:background="#aabbcc"
android:scaleType="fitStart"
android:src="@drawable/test" />
<ImageView
android:layout_width="300px"
android:layout_height="