Android drawable

A Drawable is a general abstraction for "something that can be drawn." Most often 
you will deal with Drawable as the type of resource retrieved for drawing things to 
the screen; the Drawable class provides a generic API for dealing with an underlying 
visual resource that may take a variety of forms. Unlike a View, a Drawable does not have any facility to receive events or otherwise interact with the user. 
Drawable是一个可画对象,可以用它在屏膜上画内容,也可以直接取得已的图等。
Drawable d = this.getResources().getDrawable(R.drawable.a1);
// this指代Activity, R.drawable.a1是在\res\drawable文件夹中的名称为a1的图。

常见的几种Drawable对象类型:
Bitmap: the simplest Drawable, a PNG or JPEG image. 
// 一般用于处理jpg和png图

Nine Patch: an extension to the PNG format allows it to specify information about 
how to stretch it and place things inside of it. 

Shape: contains simple drawing commands instead of a raw bitmap, allowing it to 
resize better in some cases. 

Layers: a compound drawable, which draws multiple underlying drawables on top of each other. 
LayerDrawable(Drawable[] array);
用于图层方式存取多个Drawable,可以用getDrawable(int index)取得其中一个Drawable,对应setLayer(int);

States: a compound drawable that selects one of a set of drawables based on its state.
addState(int[] stateSet, Drawable drawable); 
An array of resource Ids to associate with the image. Switch to this image by calling setState(). 
为不同的状态存取不同的Drawable,通过指定状态的id值,可以取得如获得焦点,失去焦点等时的不同图像
如:addState( new int[]{R.attr.state_focused, R.attr.state_pressed}, ... ); 对应setState(int[]);

Levels: a compound drawable that selects one of a set of drawables based on its level. 
addLevel(int low, int high, Drawable drawable)
可以指定在不同的级别中显示不同的图
如:addLevel(1, 3, ...); // 在第1到3级的时候显示相应的图,对应setLevel(int)


Scale: a compound drawable with a single child drawable, whose overall size is 
modified based on the current level. 
ScaleDrawable(Drawable drawable, int gravity, float scaleWidth, float scaleHeight)
// 这是一个可以缩放的drawable,可以将图缩放到指定的大小


例:
Drawable[] array = new Drawable[] {
this.getResources().getDrawable(R.drawable.a1),
this.getResources().getDrawable(R.drawable.a2),
this.getResources().getDrawable(R.drawable.a3),
this.getResources().getDrawable(R.drawable.a4)
};
LayerDrawable ld = new LayerDrawable( array );

ImageButton imgBtn = new ImageButton( this );
imgBtn.setImageDrawable( ld.getDrawable(2) );
// 显示a3这个图

原文地址:https://www.cnblogs.com/xingmeng/p/2395676.html