1 从一个需求说起。
界面上面有一个卡片,卡片需要动态设置其背景颜色,而这个颜色值需要从卡片上显示的图片上获取。
这就用到了这个类:
android.support.v7.graphics.Palette
Palette 可以从图像中提取突出颜色。
这个类能提取以下突出的颜色:
Vibrant(充满活力的)
Vibrant dark(充满活力的黑)
Vibrant light(充满活力的亮)
Muted(柔和的)
Muted dark(柔和的黑)
Muted lighr(柔和的亮)
2 如何使用
为了方便测试,在代码中没有给卡片设置背景颜色,而是给文字设置了背景颜色。
获取Palette 实例有两种方式:
同步:
Palette palette = Palette.from(bitmap).generate();
异步:
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
//TODO
}
});
from方法需要传入一个Bitmap对象,Palette就是从这个Bitmap中提取我们需要的颜色。
目前在项目中用同步的方法就可以。
简单实例代码:
public class MainActivity extends AppCompatActivity {
private int defaultColor ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paletteBitmapSync(BitmapFactory.decodeResource(getResources(), R.drawable.bd_1));
defaultColor = getResources().getColor(R.color.defaultColor);
}
private void paletteBitmapSync(Bitmap bitmap) {
Palette palette = Palette.from(bitmap).generate();
findViewById(R.id.vibrant).setBackgroundColor(palette.getVibrantColor(defaultColor));
findViewById(R.id.vibrant_dark).setBackgroundColor(palette.getDarkVibrantColor(defaultColor));
findViewById(R.id.vibrant_light).setBackgroundColor(palette.getLightVibrantColor(defaultColor));
findViewById(R.id.muted).setBackgroundColor(palette.getMutedColor(defaultColor));
findViewById(R.id.muted_dark).setBackgroundColor(palette.getDarkMutedColor(defaultColor));
findViewById(R.id.muted_light).setBackgroundColor(palette.getLightMutedColor(defaultColor));
}
private void paletteBitmapAsync(Bitmap bitmap) {
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
findViewById(R.id.vibrant).setBackgroundColor(palette.getVibrantColor(defaultColor));
findViewById(R.id.vibrant_dark).setBackgroundColor(palette.getDarkVibrantColor(defaultColor));
findViewById(R.id.vibrant_light).setBackgroundColor(palette.getLightVibrantColor(defaultColor));
findViewById(R.id.muted).setBackgroundColor(palette.getMutedColor(defaultColor));
findViewById(R.id.muted_dark).setBackgroundColor(palette.getDarkMutedColor(defaultColor));
findViewById(R.id.muted_light).setBackgroundColor(palette.getLightMutedColor(defaultColor));
}
});
}
}
结果: