Android UI開發專題(三) 各種Drawable

來源:互聯網
上載者:User

Android UI開發專題(三) 各種Drawable

   本次我們主要講解Android平台下的各種Drawable,這裡在SDK的android.graphics.drawable包下面可以看到有各種Drawable類多達十幾種,它們到底之間有什麼關係和區別呢?

  一、AnimationDrawable

  顧名思義該類主要表示動畫的圖形類,可以實現逐幀播放的效果,下面程式碼範例如下

  1. 定義一個cwj_animation.xml 放到res/drawable 目錄下,其中定義的屬性duration為延時,單位為毫秒,而oneshot屬性工作表示是否僅播放一次,內容為:

  Code highlighting produced by Actipro CodeHighlighter (freeware)

  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) //從輸入資料流中構造,同樣推薦下面的方法

  BitmapDrawable(Resources res, InputStream is) //同上

  在BitmapDrawable類中相對於Drawable類主要新增了以下幾種方法,均比較實用:

  final Bitmap getBitmap() 擷取一個Bitmap對象

  int getOpacity() //擷取透明度

  void setAntiAlias(boolean aa) //是否消除鋸齒

  void setTargetDensity(Canvas canvas) //設定目標Canvas密度

  void setTargetDensity(DisplayMetrics metrics)

  三、ClipDrawable

  ColorDrawable

  Drawable

  GradientDrawable

  InsetDrawable

  LayerDrawable

  LevelListDrawable

  NinePatchDrawable

  PaintDrawable

  PictureDrawable

  RotateDrawable

  ScaleDrawable

  ShapeDrawable

  StateListDrawable

  TransitionDrawable

  以上的類型在常見的開發一般較少出現,主要是基類構造使用,Android內部的多個Widget基礎控制項使用了,感興趣的網友可以查看開源GIT中的相關內容。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.