12.3 Palette" class="reference-link">12.3 Palette
在Android的版本发展中,UI越来越成为Google的发展重心。这次的Android 5.X创新地使用Palette来提取颜色,从而让主题能够动态适应当前页面的色调,做到整个App颜色基调和谐统一。
Android内置了几种提取色调的种类,如下所示。
- Vibrant(充满活力的)
- Vibrant dark(充满活力的黑)
- Vibrant light(充满活力的亮)
- Muted(柔和的)
- Muted dark(柔和的黑)
- Muted light(柔和的亮)
使用Palette的API,能够让我们从Bitmap中获取对应的色调,修改当前的主题色调。
使用Palette首先需要在Android Studio中引用相关的依赖,在项目列表上点击F4,然后在Module Setting的Dependencies选项卡中添加com.android.support:palette-v7:21.0.2引用,重新Sync项目即可。可以通过传递一个Bitmap对象给Palette,并调用它的Palette.generate()静态方法或者Palette.generateAsync()方法来创建一个Palette。接下来,就可以使用getter方法来检索相应的色调,这些色调就是我们在上面列表中所列出来的色调。
下面这个例子,演示了如何通过加载的图片的柔和色调来改变状态栏和Actionbar的色调,代码如下所示。
- package com.imooc.myapplication;
- import android.app.Activity;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.drawable.ColorDrawable;
- import android.os.Bundle;
- import android.support.v7.graphics.Palette;
- import android.view.Window;
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
- R.drawable.test);
- //创建Palette对象
- Palette.generateAsync(bitmap,
- new Palette.PaletteAsyncListener() {
- @Override
- public void onGenerated(Palette palette) {
- //通过Palette来获取对应的色调
- Palette.Swatch vibrant =
- palette.getDarkVibrantSwatch();
- //将颜色设置给相应的组件
- getActionBar().setBackgroundDrawable(
- new ColorDrawable(vibrant.getRgb()));
- Window window = getWindow();
- window.setStatusBarColor(vibrant.getRgb());
- }
- });
- }
- }
通过以下方法来提取不同色调的颜色。
- palette.getVibrantSwatch ();
- palette.getDarkVibrantSwatch ();
- palette.getLightVibrantSwatch ();
- palette.getMutedSwatch ();
- palette.getDarkMutedSwatch ();
- palette.getLightMutedSwatch ();
在如上所示代码中使用getDarkVibrantSwatch()方法提取的色调效果如图12.7所示。
图12.7 设置系统色调
