一、什麼是Palette
1.Palette:可以在一張圖片裏面分析出一些色彩特性:主色調、鮮豔的顏色、柔和顏色等等……比如:
引入v7裏面的一個單獨項目Palette:
android.support.v7.graphics.Palette;
二、使用
BitmapDrawable drawable = (BitmapDrawable) iv.getDrawable();
Bitmap bitmap = drawable.getBitmap();
//得到bitmap裏面的的一些色彩信息---通過Palette類分析出來的
// Palette palette = Palette.generate(bitmap);
//異步任務---可能分析的圖片會比較大或者顏色分佈比較複雜,會耗時比較久,防止卡死主線程。
Palette.from(bitmap).generate(new PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
//暗、柔和的顏色
int darkMutedColor = palette.getDarkMutedColor(Color.BLUE);//如果分析不出來,則返回默認顏色
//暗、柔和
int lightMutedColor = palette.getLightMutedColor(Color.BLUE);
//暗、鮮豔
int darkVibrantColor = palette.getDarkVibrantColor(Color.BLUE);
//亮、鮮豔
int lightVibrantColor = palette.getLightVibrantColor(Color.BLUE);
//柔和
int mutedColor = palette.getMutedColor(Color.BLUE);
//柔和
int vibrantColor = palette.getVibrantColor(Color.BLUE);
//獲取某種特性顏色的樣品
// Swatch lightVibrantSwatch = palette.getLightVibrantSwatch();
Swatch lightVibrantSwatch = palette.getVibrantSwatch();
//谷歌推薦的:圖片的整體的顏色rgb的混合值---主色調
int rgb = lightVibrantSwatch.getRgb();
//谷歌推薦:圖片中間的文字顏色
int bodyTextColor = lightVibrantSwatch.getBodyTextColor();
//谷歌推薦:作爲標題的顏色(有一定的和圖片的對比度的顏色值)
int titleTextColor = lightVibrantSwatch.getTitleTextColor();
//顏色向量
float[] hsl = lightVibrantSwatch.getHsl();
//分析該顏色在圖片中所佔的像素多少值
int population = lightVibrantSwatch.getPopulation();
tv_title.setBackgroundColor(getTranslucentColor(0.6f,rgb));
tv_title.setTextColor(titleTextColor);
tv1.setBackgroundColor(darkMutedColor);
tv1.setText("darkMutedColor");
tv2.setBackgroundColor(lightMutedColor);
tv2.setText("lightMutedColor");
tv3.setBackgroundColor(darkVibrantColor);
tv3.setText("darkVibrantColor");
tv4.setBackgroundColor(lightVibrantColor);
tv4.setText("lightVibrantColor");
tv5.setBackgroundColor(mutedColor);
tv5.setText("mutedColor");
tv6.setBackgroundColor(vibrantColor);
tv6.setText("vibrantColor");
}
});
將某個顏色值加入透明度:
/**
* 1101 0111 1000 1011
* 1111 1111
* 1000 1011
*/
protected int getTranslucentColor(float percent, int rgb) {
// 10101011110001111
int blue = Color.blue(rgb);
int green = Color.green(rgb);
int red = Color.red(rgb);
int alpha = Color.alpha(rgb);
// int blue = rgb & 0xff;
// int green = rgb>>8 & 0xff;
// int red = rgb>>16 & 0xff;
// int alpha = rgb>>>24;
alpha = Math.round(alpha*percent);
Toast.makeText(this, "alpha:"+alpha+",red:"+red+",green:"+green, 1).show();
return Color.argb(alpha, red, green, blue);
}
也可以使用ColorUtils的方法