Palette顏色提取使用詳解
如果你試過android Lollipop的sdk,你可能注意到了Palette。Palette從圖像中提取突出的顏色,這樣可以把色值賦給ActionBar、或者其他,可以讓界面整個色調統一。
創建Palette實例
有四種創建實例的方法:
// Synchronous methods. // -------------------------------- // These should be used when you have access to the underlying image loading thread. // Picasso allows this through a Transformation. For other libraries, YMMV. // Uses the default palette size (16). Palette p = Palette.generate(bitmap); // Allows you to specify the maximum palette size, in this case 24. Palette p = Palette.generate(bitmap, 24); // Asynchronous methods // -------------------------------- // This is the quick and easy integration path. Internally uses an AsyncTask so // this may not be optimal (since you're dipping in and out of threads) // Uses the default palette size (16). Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() { @Override public void onGenerated(Palette palette) { // Here's your generated palette } }); // Allows you to specify the maximum palette size, in this case 24. Palette.generateAsync(bitmap, 24, new Palette.PaletteAsyncListener() { @Override public void onGenerated(Palette palette) { // Here's your generated palette } });
創建完一個實例之后,我們還需要得到一種采集的樣本(swatch),有6中樣本(swatch):
Vibrant. Palette.getVibrantSwatch() Vibrant dark. Palette.getDarkVibrantSwatch() Vibrant light. Palette.getLightVibrantSwatch() Muted. Palette.getMutedSwatch() Muted dark. Palette.getDarkMutedSwatch() Muted light. Palette.getLightMutedSwatch()
具體選擇哪一種取決于你自己,大多數情況下我們都使用Vibrant and Dark Vibrant。
使用樣本(swatch)
swatch有以下方法:
getPopulation(): the amount of pixels which this swatch represents. getRgb(): the RGB value of this color. getHsl(): the HSL value of this color. getBodyTextColor(): the RGB value of a text color which can be displayed on top of this color. getTitleTextColor(): the RGB value of a text color which can be displayed on top of this color.
比如如果你的TextView 有個背景圖片,要想讓字體顏色能夠和背景圖片匹配,則使用getBodyTextColor()
比較合適,getTitleTextColor()
其實應該和getBodyTextColor()
差不多。
下面的代碼則是展示了如何從一張圖片中提取顏色將textView的背景色設置成圖片的主色調,然后再使用getTitleTextColor
()來設置一個匹配的文字顏色。
Palette.Swatch swatch = palette.getVibrantSwatch(); TextView titleView = ...; if (swatch != null) { titleView.setBackgroundColor(swatch.getRgb()); titleView.setTextColor(swatch.getTitleTextColor()); }
需要注意的是getVibrantSwatch()
可能會返回一個null值,所以檢查一下是必須的。
size的問題
你還可以使用如下方法一次性獲得所有的swatch:
List<Palette.Swatch> swatches = palette.getSwatches();
在上面的代碼中,你可能注意到了可以設置palette的size。size越大,花費的時間越長,而越小,可以選擇的色彩也越小。最佳的選擇是根據image的用途:
頭像之類的,size最好在24-32之間;
風景大圖之類的 size差不多在8-16;
默認是16.
本文由用戶 iojkjk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!