編輯:關於 Android 程式設計
什麼是 Drawable
Drawable 是一個抽象類,表示可以在 Canvas 中繪製的圖像,常被用作 View 的背景,有多種實現類完成不同功能。大致可分為「圖片」和「由顏色構成的圖像」兩類,一般用 XML 定義。
Drawable 的繼承體系

Drawable 的實現類及標簽

內部寬高的獲取
getIntrinsicHeight、getIntrinsicWidth:
- 當 Drawable 由圖片構成時,返回的是圖片的寬高;
- 當 Drawable 由顏色構成時則沒有寬高概念,返回 -1。
用於顯示一張圖片,示例如下:
<?xml version="1.0" encoding="utf-8"?> <bitmap xmlns:android="https://schemas.android.com/apk/res/android" android:antialias="true" android:dither="true" android:filter="true" android:gravity="top" android:src="@mipmap/girl" android:tileMode="repeat" />
常用屬性:android:antialias 是否開啟抗鋸齒;android:dither 是否開啟防抖動;android:filter 是否開啟過濾效果;android:gravity 對圖片定位;android:src 圖片資源 id;android:tileMode 平鋪模式(repeat、mirror、clamp 三種)。
代表單色可繪製區域,包裝了一種固定顏色,在畫布上繪製一塊單色區域。示例:
<?xml version="1.0" encoding="utf-8"?> <color xmlns:android="https://schemas.android.com/apk/res/android" android:color="@color/colorAccent"> </color>
也可以用代碼創建:
ColorDrawable drawable = new ColorDrawable(int color); //傳入一個 color 的 integer 值
即 9-patch 圖,可根據內容自由縮放寬高而不失真。示例:
<?xml version="1.0" encoding="utf-8"?> <nine-patch xmlns:android="https://schemas.android.com/apk/res/android" android:dither="true" android:filter="true" android:src="@color/colorAccent"> </nine-patch>
用 draw9patch 設定縮放區域:圖中 1、2 方向繪製的黑線,其長度交集為可拉伸範圍;3、4 方向黑線的長度交集表示內容可填充的區域。

通過顏色構造圖形,既可以是純色圖形,也可以是漸變圖形,能構成的形狀有 rectangle、oval、ring、line。
具有漸變效果的圓示例:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="https://schemas.android.com/apk/res/android" android:shape="oval"> <gradient android:angle="45" android:centerColor="@color/colorAccent" android:centerX="50%" android:centerY="50%" android:endColor="@color/colorPrimary" android:gradientRadius="150dp" android:startColor="@color/colorPrimaryDark" android:type="sweep" /> <size android:width="260dp" android:height="260dp" /> </shape>
注意:android:angle 值必須為 45 的倍數;oval 用於繪制橢圓,當 size 的寬高相等時繪制成圓。
圓環示例:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="https://schemas.android.com/apk/res/android" android:innerRadius="100dp" android:shape="ring" android:thickness="10dp" android:useLevel="false" > <stroke android:width="10dp" android:color="@color/colorAccent" /> </shape>
注:android:useLevel 設置為 false,否則無法顯示理想效果;innerRadius 為圓環內半徑,innerRadiusRation 為內半徑占圓環寬度的比率,兩者以 innerRadius 為主;thickness 為圓環寬度,thicknessRatio 為此寬度占圓環寬度的比率,以 thickness 為主。
常用屬性:
- android:shape 要繪制的形狀(rectangle、oval、ring、line)
- <stroke> 形狀的描邊:android:width 描邊寬度、android:color 描邊顏色、android:dashGap 虛線線寬、android:dashWidth 虛線線段間隔(繪製虛線時後兩者均不能為 0)
- <solid> 純色填充,android:color 指定 shape 顏色
- <gradient> 漸變效果,與 solid 不可共用:android:angle 漸變角度(必須為 45 的倍數)、android:startColor 起始色、android:centerColor 中間色、android:endColor 結束色、android:centerX/Y 漸變中心點、android:gradientRadius 漸變半徑、android:type 漸變類型(linear 線性、sweep 掃視、radial 徑向)
- <corners> 矩形四角角度(不適用其他 shape):android:topLeftRadius、topRightRadius、bottomLeftRadius、bottomRightRadius 分別設置四角,android:radius 為四角設相同角度(優先級低,會被覆蓋)
- <size> shape 的寬高(android:width、android:height),默認無寬高,getIntrinsic 返回 -1;作為 view 背景時仍會被拉伸為 view 大小
- <padding> 設置容納 shape 的 view 的空白間距
可看作狀態選擇器,根據 view 的不同狀態選擇對應 item 中的 drawable 顯示。示例:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="https://schemas.android.com/apk/res/android"> <item android:drawable="@color/colorPrimaryDark" android:state_pressed="false"></item> <item android:drawable="@color/colorAccent" android:state_pressed="true"></item> </selector>
常見狀態:android:state_pressed 按住時;android:state_checked 被選中時(適用 CheckBox);android:state_selected 被選擇時;android:state_enabled 可用狀態;android:state_focused 獲取焦點時。
表示分層的 Drawable 集合,類似 PS 中的圖層概念,將多個 drawable 疊加呈現效果。示例:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="https://schemas.android.com/apk/res/android"> <item android:drawable="@mipmap/night" /> <item android:drawable="@mipmap/photo6" android:gravity="center" /> </layer-list>
注意:layer-list 可包含多個 item,後添加的會覆蓋之前的;默認所有 drawable 都會縮放至 view 大小,可用 android:gravity 調節;還可設置上下左右偏移量 android:top、bottom、left、right。
表示一個 drawable 集合,每個 Drawable 都有一個等級(level),通過設置不同等級切換不同的 Drawable,等級範圍 0~10000,android:maxLevel 設最大 level,android:minLevel 設最小 level。示例:
<?xml version="1.0" encoding="utf-8"?> <level-list xmlns:android="https://schemas.android.com/apk/res/android"> <item android:drawable="@mipmap/photo0" android:maxLevel="20" android:minLevel="10" /> <item android:drawable="@mipmap/photo1" android:maxLevel="40" android:minLevel="30" /> </level-list>
通過設置 level 切換不同 Drawable:
//將ImageView的背景切換為photo1, 35 在30~40之間 iv.setImageLevel(35); //將ImageView的背景切換為photo0, 15在10~20之間 iv.setImageLevel(15);
LayerDrawable 的子類,用於實現兩個 Drawable 的淡入淡出效果。
XML 定義:
<?xml version="1.0" encoding="utf-8"?> <transition xmlns:android="https://schemas.android.com/apk/res/android"> <item android:drawable="@mipmap/night" /> <item android:drawable="@mipmap/photo6" /> </transition>
給 ImageView 設置 src 後,在 Java 代碼中:
iv= (ImageView) findViewById(R.id.iv_transition); drawable = (TransitionDrawable) iv.getDrawable(); drawable.startTransition(1000); // 實現淡入淡出效果 drawable.reverseTransition(1000);
嵌入其他 Drawable,並可在四周保留一定間距。示例:
<?xml version="1.0" encoding="utf-8"?> <inset xmlns:android="https://schemas.android.com/apk/res/android" android:drawable="@mipmap/photo6" android:inset="20dp"> </inset>
根據等級將一個 Drawable 縮放到一定比例,level 為 0 時不可見,為 10000 時無縮放效果。示例:
<?xml version="1.0" encoding="utf-8"?> <scale xmlns:android="https://schemas.android.com/apk/res/android" android:drawable="@mipmap/night" android:scaleGravity="center" android:scaleHeight="50%" android:scaleWidth="50%" />
要顯示效果,必須設置 level 大於 0:
iv = (ImageView) findViewById(R.id.iv_scale); ScaleDrawable drawable= (ScaleDrawable) iv.getDrawable(); drawable.setLevel(1);
- android:scaleHeight="percentage"、android:scaleWidth="percentage" 設置寬高縮放為原來的比例(100% - percentage);
- 設置 level 越大,圖像顯示越大。
根據自己的等級(level)對另一個 Drawable 進行裁剪,裁剪方向由 android:clipOrientation 與 android:gravity 共同決定。level 從 0 到 10000,為 0 時完全不顯示,為 10000 時完全顯示。
XML 定義:
<?xml version="1.0" encoding="utf-8"?> <clip xmlns:android="https://schemas.android.com/apk/res/android" android:clipOrientation="horizontal" android:drawable="@mipmap/night" android:gravity="right"></clip>
<ImageView android:id="@+id/iv_clip" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/drawable_clip" />
通過設置 level 裁剪:
ImageView iv = (ImageView) findViewById(R.id.iv_clip); ClipDrawable drawable= (ClipDrawable) iv.getDrawable(); drawable.setLevel(5000); // 設置的level越大裁剪的范圍越小
屬性:android:clipOrientation(horizontal 水平裁剪、vertical 垂直裁剪)、android:gravity(配合裁剪方向)。

自定義圓形 Drawable:
package com.yu.drawablelearing; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Shader; import android.graphics.drawable.Drawable; public class CircleDrawable extends Drawable{ private int radius; private int mWidth; private int mHeight; private Paint mPaint; @Override public void draw(Canvas canvas) { canvas.drawCircle(mWidth/2,mHeight/2,radius,mPaint); } public CircleDrawable(Bitmap bitmap) { radius = Math.min(bitmap.getWidth(), bitmap.getHeight())/2; mWidth = bitmap.getWidth(); mHeight = bitmap.getHeight(); BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mPaint = new Paint(); mPaint.setShader(bitmapShader); mPaint.setAntiAlias(true); } @Override public void setAlpha(int alpha) { mPaint.setAlpha(alpha); invalidateSelf(); } @Override public void setColorFilter(ColorFilter colorFilter) { mPaint.setColorFilter(colorFilter); invalidateSelf(); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public int getIntrinsicHeight() { return mHeight; } @Override public int getIntrinsicWidth() { return mWidth; } }
自定義帶圓角的矩形 Drawable:
package com.yu.drawablelearing; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Drawable; /** * Created by pecu on 2016/08/24. */ public class RoundRectangleDrawable extends Drawable { private RectF rectF; private Paint mPaint; Bitmap mBitmap; @Override public void draw(Canvas canvas) { canvas.drawRoundRect(rectF, mBitmap.getWidth()/6,mBitmap.getHeight()/6, mPaint); } public RoundRectangleDrawable(Bitmap bitmap) { mBitmap = bitmap; mPaint = new Paint(); BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mPaint.setAntiAlias(true); mPaint.setShader(bitmapShader); } @Override public void setAlpha(int alpha) { mPaint.setAlpha(alpha); invalidateSelf(); } @Override public void setColorFilter(ColorFilter colorFilter) { mPaint.setColorFilter(colorFilter); invalidateSelf(); } @Override public void setBounds(int left, int top, int right, int bottom) { super.setBounds(left, top, right, bottom); rectF = new RectF(left, top, right, bottom); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public int getIntrinsicWidth() { return mBitmap.getWidth(); } @Override public int getIntrinsicHeight() { return mBitmap.getHeight(); } }
自定義 Drawable 的一般步驟:
1. 自定義 Drawable 類繼承自 Drawable;
2. 實現 getOpacity、setColorFilter、setAlpha 等方法;
3. 在 draw 方法中進行繪制;
4. 若有固定大小,則需實現 getIntrinsicWidth、getIntrinsicHeight。
以上就是本文的全部內容,希望對大家的學習有所幫助。
Android View 測量機制解析:從 MeasureSpec 到自定義 wrap_content
在 Android 介面開發中,View 的測量是理解佈局與自定義元件的核心起點。一句話概括:只要知道可用位置與尺寸限制,View 就能決定自己最終要畫成多大。 可以把
React Native 實戰:手把手打造自定義頂部導航欄
經過前幾篇的學習積累,我們已經具備了實現一個自定義導航欄的能力,最終效果如下: 整體思路是:創建一個 NaviBar.js 用於渲染頂部導航欄,再準備四個頁面(Page
Android Studio 打包時自動把版本號與版本名稱寫進 APK 檔名
Android Studio 打包出來的 apk 預設叫 app-debug.apk。一款 App 迭代幾輪之後,你的資料夾裡就會躺著五六個同名檔案,這時候想確認「這個
深入 Android Handler:用消息佇列實作執行緒間通信 ITC
Handler 是操作執行緒內部消息佇列的類。正因為它能操作佇列,也就順帶成為執行緒間通信(ITC,Inter Thread Communication)的手段——這種方