前言
去年Google发布了android5.0 新增了了很多内容,其中包括了Palette 类 为什么讲它,很简单因为Google在support.V7中也发布了兼容的版本,so 不用考虑低版本是否支持了。
简介
Palette 翻译过来叫做调色板 Google的解释是:"lets you extract prominent colors from an image" 可以从一张图片中提取较为突出的颜色,比如一个音乐播放器 这播放界面的时候一般都会显示一张专辑的图片在中间(网易云音乐,,QQ音乐 etc)而且这张图片一般会占据着很大的空间,这个时候为了让整个界面的颜色风格一致,就可以从这张专辑的图片中提取颜色了,然后在把颜色应用到其他的widget就可以了。
用法
Palette提供了四种静态的方法来提取图片的颜色,其实主要就是同步和异步的区别,generateAync(Bitmap ,PaletteAsyncListener) ,generate(Bitmap) ,考虑到提起颜色有可能是一个耗时的操作,所以尽量使用异步的方式
<span style="font-size:18px;">public class PaletteActivity extends ActionBarActivity implements
PaletteAsyncListener {
Bitmap bitmap;
Button mButton1, mButton2, mButton3 ,mButton4;
ImageView mImageView;
private int resIds[] = new int[] { R.drawable.pic_one, R.drawable.pic_two,
R.drawable.pic_three };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_palette);
mImageView=(ImageView)findViewById(R.id.imageview);
mButton1 = (Button) findViewById(R.id.button);
mButton2 = (Button) findViewById(R.id.button2);
mButton3 = (Button) findViewById(R.id.button3);
mButton4 =(Button)findViewById(R.id.button4);
Random random = new Random();
int index = random.nextInt(3);
bitmap = BitmapFactory.decodeResource(getResources(), resIds[index]);
mImageView.setImageBitmap(bitmap);
Palette.generateAsync(bitmap, this);
}
@Override
public void onGenerated(Palette palette) {
Swatch darkMutedSwatch = palette.getDarkMutedSwatch();
Swatch darkVibrantSwatch = palette.getDarkVibrantSwatch();
Swatch lightMutedSwatch = palette.getLightMutedSwatch();
Swatch lightVibrantSwatch = palette.getLightVibrantSwatch();
if(darkMutedSwatch!=null)
mButton1 .setBackgroundColor(darkMutedSwatch.getRgb());
if(darkVibrantSwatch!=null)
mButton2.setBackgroundColor(darkVibrantSwatch.getRgb());
if(lightMutedSwatch!=null)
mButton3.setBackgroundColor(lightMutedSwatch.getRgb());
if(lightVibrantSwatch!=null)
mButton4.setBackgroundColor(lightVibrantSwatch.getRgb());
}
}</span>
效果
下面是分别使用了三张图片来提取颜色,主要是有的按钮的颜色没有提取到,因为图片没有对于的颜色 比如你想如图Dark的颜色 但是图片是一张非常Light的图片 so 必须判断是否为空,不然会报NullPointException