本人所有文章首先發(fā)布于個(gè)人博客,歡迎關(guān)注,地址:http://blog.isming.me
以下Drawables的功能幫助你在應(yīng)用中實(shí)現(xiàn)Material Design:
圖片資源著色
在android 5.0(api 21)和更高版本,可以著色bitmap和.9 png 通過(guò)定義透明度遮蓋。你可以著色通過(guò)使用顏色資源或者主題的屬性去解析顏色資源(比如,?android:attr/colorPrimary
).通常我們創(chuàng)建一次,然后資源自適應(yīng)主題。
你可以給BitmapDrawable或NinePatchDrawable對(duì)象著色使用setTint()
方法。你可以可以在布局文件中使用android:tint
和android:tintMode
屬性設(shè)置著色顏色和著色模式。
從圖片中抽取高亮顏色
support library r21和更高的版本中包括了Palette
類(lèi),可以從一個(gè)圖片中提取高亮顏色。這個(gè)類(lèi)可以提起以下幾種突出顏色:
Vibrant 充滿生機(jī)
Vibrant dark 暗的充滿生機(jī)
Vibrant light 亮的充滿生機(jī)
Muted 柔和
Muted dark 暗的柔和
Muted light 亮的柔和
傳遞一個(gè)Bitmap對(duì)象給靜態(tài)方法Palette.generate(),它會(huì)在后臺(tái)線程幫你從后臺(tái)線程提取顏色。如果你不能使用這個(gè)后臺(tái)線程,使用Palette.generateAsync()方法,并且設(shè)置一個(gè)監(jiān)聽(tīng)器listener.
你可以從圖片中取得突出顏色使用Palette類(lèi)中的getter方法,比如Palette.getVibrantColor.
在項(xiàng)目中使用Palette方法,需要在項(xiàng)目中包含v7包palette的jar, gradle dependecy添加的方式是:
...
compile 'com.android.support:palette-v7:21.0.+'
下面這個(gè)是示例代碼:
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
// Do something with colors...
palette.getVibrantColor(Color.BLACK); //get a color in rgb value
}
});

更多信息,請(qǐng)查看Paltette的api文檔:http://developer.android.com/reference/android/support/v7/graphics/Palette.html
創(chuàng)建矢量drawables
在android 5.0和更高版本中,可以創(chuàng)建矢量的drawable,在縮放的時(shí)候不會(huì)失真。你只需要定義一個(gè)矢量圖片文件,相反的,使用bitmap位圖則需要針對(duì)不同的分辨率創(chuàng)建多個(gè)文件。創(chuàng)建一個(gè)矢量圖片,你需要說(shuō)明圖形的詳細(xì),在xml文件的<vector>標(biāo)簽下。
下面是一個(gè)例子:
<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/heart.xml -->
<vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:width="256dp"
android:height="256dp"
android:viewportHeight="32"
android:viewportWidth="32">
<!-- draw a path -->
<path
android:fillColor="#f15467"
android:pathData="M20.5,9.5
c-1.955,0,-3.83,1.268,-4.5,3
c-0.67,-1.732,-2.547,-3,-4.5,-3
C8.957,9.5,7,11.432,7,14
c0,3.53,3.793,6.257,9,11.5
c5.207,-5.242,9,-7.97,9,-11.5
C25,11.432,23.043,9.5,20.5,9.5z"/>
</vector>
上面的圖顯示效果如下:

矢量圖片在android表現(xiàn)為VectorDrawable
對(duì)象。更多信息,查看Svg Path reference。
參考資料:http://developer.android.com/training/material/drawables.html
原文地址:http://blog.isming.me/2014/11/03/creating-app-with-material-design-four-drawables/,轉(zhuǎn)載請(qǐng)注明出處。