前段時間項目不著急,想到對 Drawable 這個知識點不熟悉,所以就想著通過練習(xí)寫自定義 Drawable 來熟悉下。
Drawable 簡介(翻譯自 Google 文檔)
Drawable 是 可繪制對象 的抽象,與 android.view.View
不同,Drawable 沒有任何功能接收事件或其他方式與用戶交互靴迫。
Android 的所有版本都允許在運行時擴展和使用 Drawable
類代替框架提供的 drawable
類。在 API 24 開始楼誓,可以在 XML 中使用自定義 Drawable 玉锌。
注意:自定義 Drawable 只能在應(yīng)用程序中訪問,其他應(yīng)用程序?qū)o法加載它們疟羹。
自定義 Drawable 至少必須在 Drawable 上實現(xiàn)抽象方法主守,并且應(yīng)該覆蓋 draw(Canvas)
方法來繪制內(nèi)容禀倔。
可以以多種方式在 XML 中使用自定義 Drawable 類:
-
使用完全限定類名作為 XML 元素名稱。對于此方法丸逸,自定義 drawable 類必須是公共頂級類蹋艺。
<com.example.CustomDrawable xmlns:android="http://schemas.android.com/apk/res/android"/>
-
使用 drawable 作為 XML 元素名稱,并從類屬性中指定完全限定的類名黄刚。此方法可用于公共頂層類和公共靜態(tài)內(nèi)部類捎谨。
<drawable xmlns:android="http://schemas.android.com/apk/res/android" class="com.example.TopDrawable$CustomDrawable" />
Drawable.ConstantState
ConstantState 用于在不同的 Drawable 之間保存共同的恒定狀態(tài)和數(shù)據(jù)。例如:從同一個資源創(chuàng)建的 BitmapDrawables
將共享保存在它們的 ConstantState 中的同一個單獨的 Bitmap憔维。
newDrawable(Resources)
可以作為一個工廠類被用來創(chuàng)建新的 Drawable 從當前的 ConstantState涛救。
使用 getConstantSatte()
從一個 Drawable中取回 ConstantState。
在 Drawable 中調(diào)用 mutate()
通常應(yīng)該為這個 Drawable 創(chuàng)建一個新的 ConstantState业扒。
自定義 Drawable 局限性
- 動態(tài)改變 Drawable 繪制的尺寸屬性(比如检吆,繪制的變局或者其中文字的大小),需要調(diào)用設(shè)置了 Drawable 的對象(一般為 View )去重新測量尺寸程储。
getBounds
方法可能返回不同的尺寸蹭沛,但真實尺寸可能不會改變。
自定義 Drawable 實現(xiàn)抽象方法
//返回 Drawable 的真實尺寸章鲤。用于設(shè)置了 Drawable 的對象在測量時摊灭,考慮的合適尺寸
@Override
public int getIntrinsicWidth() {
return mIntrinsicWidth;
}
@Override
public int getIntrinsicHeight() {
return mIntrinsicHeight;
}
//返回當前 Drawable 為透明/不透明
public abstract @PixelFormat.Opacity int getOpacity();
實踐
github 地址