Palette顾名思义调色板, Palette的作用是可以从图像中提取图片的颜色。我们可以把提取的颜色融入到App UI中,可以使UI风格更加美观融洽。有些时候Palette显得非常好用,比如我们可以提取到的突出的色值设置为Toolbar,标题,状态栏的颜色等,可以使我们的整个界面色调统一,效果非常好看。
添加依赖:
compile 'com.android.support:palette-v7:25.3.1'
获取图片bitmap
Resources res = getResources(); Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.ic_zc_banner2);
获的图片的Palette对象
Palette.Builder builder = Palette.from(bitmap);
由于解析图片可能是比较耗时的操,所以需要在非UI线程中操作 Palette提供了PaletteAsyncListener,只需要在onGenerated()中直接使用获取到的对象即可
Palette提供了6种方法获取对应颜色的Swatch对象 然后使用Swatch的相关方法就可以获取到相应的颜色值
Palette.PaletteAsyncListener listener = new Palette.PaletteAsyncListener() { public void onGenerated(Palette palette) { // 使用Palette对象,获取解析出的颜色 Palette.Swatch s1 = palette.getVibrantSwatch(); //获取到充满活力的这种色调 Palette.Swatch s2 = palette.getDarkVibrantSwatch(); //获取充满活力的黑 Palette.Swatch s3 = palette.getLightVibrantSwatch(); //获取充满活力的亮 Palette.Swatch s4 = palette.getMutedSwatch(); //获取柔和的色调 Palette.Swatch s5 = palette.getDarkMutedSwatch(); //获取柔和的黑 Palette.Swatch s6 = palette.getLightMutedSwatch(); //获取柔和的亮 TextView tv1 = (TextView) findViewById(R.id.view1); TextView tv2 = (TextView) findViewById(R.id.view2); TextView tv3 = (TextView) findViewById(R.id.view3); TextView tv4 = (TextView) findViewById(R.id.view4); TextView tv5 = (TextView) findViewById(R.id.view5); TextView tv6 = (TextView) findViewById(R.id.view6); if (null != s1) { tv1.setBackgroundColor(s1.getRgb()); tv1.setText("充满活力的色调"); } else { tv5.setText("没有获取到颜色对象"); } if (null != s2) { tv2.setBackgroundColor(s2.getRgb()); tv2.setText("充满活力的黑"); } else { tv5.setText("没有获取到颜色对象"); } if (null != s3) { tv3.setBackgroundColor(s3.getRgb()); tv3.setText("充满活力的亮"); } else { tv5.setText("没有获取到颜色对象"); } if (null != s4) { tv4.setBackgroundColor(s4.getRgb()); tv4.setText("柔和的色调"); } else { tv5.setText("没有获取到颜色对象"); } if (null != s5) { tv5.setBackgroundColor(s5.getRgb()); tv5.setText("柔和的黑"); } else { tv5.setText("没有获取到颜色对象"); } if (null != s6) { tv6.setBackgroundColor(s6.getRgb()); tv6.setText("柔和的亮"); } else { tv5.setText("没有获取到颜色对象"); } } };
添加监听事件
builder.generate(listener);
Swatch还提供了其他方法获取对应的颜色值
getPopulation(): 像素的数量
getRgb(): RGB颜色
getHsl(): HSL颜色
getBodyTextColor(): 用于内容正文文本的颜色
getTitleTextColor(): 标题文本的颜色
Palette只为六种主颜色种类Swatch提供了getter,如果你要使用其他颜色种类的Swatch(一共有16种颜色种类),你需要手动获取它。调用getSwatchs()会返回一个列表,里面有所有获取到的Swatch。
List<Palette.Swatch> swatches = palette.getSwatches();
源码地址:https://github.com/gaojiangmin/Palette