Android應用開發——Drawable

Android提供了一個自定義的2D圖形庫,它可以繪製形狀和圖片。在android.graphics.drawable包中可以找到普通類來繪製2D圖形。Drawable子類中包含了許多特定類型的圖形,像BitmapDrawable,ShapeDrawable,PictureDrawable,LayerDrawable等等。當然,也可以通過繼承這些類來實現自己的Drawable對象。


有三種定義和實例化Drawable的方法:

  1. 引用圖片資源方式。(res/drawable)
  2. 使用圖片資源的XML方式。
  3. 使用普通的類構造器方法。

引用圖片資源

可以把PNG (preferred), JPG (acceptable) and GIF (discouraged)的圖片格式放在項目的res/drawable目錄中,然後在項目中引用這些資源。

Notice:放在res/drawable目錄下的文件都會自動地經過aapt工具壓縮優化,如果想要得到圖片文件完整的二進制數據,可以把圖片文件放在res/raw目錄下。

假設在res/drawable中有一張my_image.png的圖片,那麼

在ImageView中使用圖片資源:

// Instantiate an ImageView and define its properties
  ImageView i = new ImageView(this);
  i.setImageResource(R.drawable.my_image);
  i.setAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's dimensions
  i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,
  LayoutParams.WRAP_CONTENT));

獲取該圖片的Drawable對象:

Resources res = mContext.getResources();
    Drawable myImage = res.getDrawable(R.drawable.my_image);

在XML文件中引用圖片資源:

<ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:tint="#55ff0000"
      android:src="@drawable/my_image"/>

使用圖片資源的XML方式

當你需要你的圖片資源在使用的時候能改變它的屬性,那麼就應該使用XML方式:res/drawable/expand_collapse.xml
 <transition xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:drawable="@drawable/image_expand">
      <item android:drawable="@drawable/image_collapse">
 </transition>

通過硬代碼實例化資源:
Resources res = mContext.getResources();
      TransitionDrawable transition = (TransitionDrawable)
res.getDrawable(R.drawable.expand_collapse);
      ImageView image = (ImageView) findViewById(R.id.toggle_image);
      image.setImageDrawable(transition);

這個transitionDrawable可以在1秒後轉變:
transition.startTransition(1000);




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章