8.3.3 图像、图形和动画
在Android中,图形和图像相关的资源文件,都放在drawable目录下;在代码中,可以通过R.drawable类来进行访问:
//sample就是资源文件的名称(除后缀外)
textView.setBackgroundResource(R.drawable.sample);
drawable目录除了可以为png、jpg、gif等格式的数据文件提供图像信息,还可以用xml文件来描述一个图像或图形文件。在实际开发中,有时候控件背景需要是能够自适应屏幕尺寸的渐变色,这样的背景无法通过简单的图像文件来提供(在Android中,也可以使用draw9格式的文件来满足此类需求,详情请参见第10章),在Android中,可以通过xml图形资源文件进行绘制,比如:
<?xml version="1.0"encoding="utf-8"?>
<!—白到黑的一个渐变—>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#ffffff"
android:endColor="#000000"/>
</shape>
或者,也可以通过拼接小的图片片段进行绘制:
<?xml version="1.0"encoding="utf-8"?>
<!—将图像bitmap_clip进行平铺,构造该图像—>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/bitmap_clip"
android:tileMode="repeat"/>
应用运行时,图形或图像资源文件都会加载成为一个android.graphics.drawable.Drawable对象,其中,位图数据文件、XML资源文件都会加载成为BitmapDrawable对象;而图形资源文件,则会加载成为ShapeDrawable对象。
Android提供的各个Drawable对象,都有与之对应的资源文件[1],其中,StateListDrawable是最为常用的一种Drawable对象。它由若干个图形或图像构成,在不同的状态下显示不同的图像信息。StateListDrawable对象常被用作按钮背景,使按钮在常态时呈现一种背景,而被点击时切换至另一种背景。使用资源文件,可以便捷地构造StateListDrawable对象:
<?xml version="1.0"encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!—被按下时显示—>
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed"/>
<!—有焦点时显示—>
<item android:state_focused="true"
android:drawable="@drawable/button_focused"/>
<!—其他状态下显示—>
<item android:drawable="@drawable/button_normal"/>
</selector>
通过资源文件,构造Drawable对象,可以有效地将界面信息从代码中分离出来,独立地进行编写和维护。使得不论图像信息如何变化,都不会影响到编码内容。
动画与图像的状况有些相近。动画资源文件放在anim目录下,全部通过值类型的XML资源文件进行描述。每个动画资源文件都可以加载成为android.view.animation.Animation对象,通过结构化的XML元素,来描述动画的构造和帧信息[2]。
[1]对应关系参见:http://developer.android.com/guide/topics/resources/drawable-resource.html。
[2]http://androidappdocs.appspot.com/guide/topics/resources/animation-resource.html。