本次我們主要講解Android平臺下的各種Drawable,這里在SDK的android.graphics.drawable包下面可以看到有各種Drawable類多達十幾種,它們到底之間有什么關系和區別呢?
一、AnimationDrawable
顧名思義該類主要表示動畫的圖形類,可以實現逐幀播放的效果,下面代碼示例如下
1. 定義一個cwj_animation.xml 放到res/drawable 目錄下,其中定義的屬性duration為延時,單位為毫秒,而oneshot屬性表示是否僅播放一次,內容為:
Code highlighting produced by Actipro CodeHigh
http://www.CodeHighlighter.com/
-->1
2
3
4
5
6
7
8animation-list>
9
10
2.在java中調用也很簡單
ImageView img = (ImageView)findViewById(R.id.cwj_image); //首先聲明一個ImageView對象在xml布局文件中
img.setBackgroundResource(R.drawable.cwj_animation); //我們剛才的animation定義的xml文件
AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground(); //構造AnimationDrawable對象
frameAnimation.start() //開始播放動畫
3. AnimationDrawable類還提供了一些常用的方法如下:
void stop() 停止
void addFrame(Drawable frame, int duration) 添加一幀,類似xml中的布局
Drawable getFrame(int index) 返回某幀的Drawable圖形
int getNumberOfFrames() 返回總共動畫幀數
boolean isOneShot() 是否僅播放一次
boolean isRunning() 是否正在播放
二、BitmapDrawable
在Android平臺中對于縮放、變形的Bitmap對象由BitmapDrawable類表示,其構造方法也很簡單,由于該類繼承于android.graphics.drawable.Drawable,相對Drawable而言提供了更多的有關位圖的操作方法,主要的構造方法如下:
BitmapDrawable() //直接構造一個空的對象,這樣方式不推薦使用,SDK標記為deprecated.未來可能無法使用。
BitmapDrawable(Resources res) //從資源中構造
BitmapDrawable(Bitmap bitmap) //從Bitmap對象直接構造,但也是不推薦,而是希望用下一種
BitmapDrawable(Resources res, Bitmap bitmap) //從bitmap中創建設置初始的分辨率從res中
BitmapDrawable(String filepath) //從具體文件路徑構造,也不推薦使用,而是下一種更好
BitmapDrawable(Resources res, String filepath) //同上
BitmapDrawable(InputStream is) //從輸入流中構造,同樣推薦下面的方法
新聞熱點
疑難解答