• 12.3 Palette" level="2">12.3 Palette

    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的色调,代码如下所示。

    1. package com.imooc.myapplication;
    2.  
    3. import android.app.Activity;
    4. import android.graphics.Bitmap;
    5. import android.graphics.BitmapFactory;
    6. import android.graphics.drawable.ColorDrawable;
    7. import android.os.Bundle;
    8. import android.support.v7.graphics.Palette;
    9. import android.view.Window;
    10.  
    11. public class MainActivity extends Activity {
    12.  
    13. @Override
    14. protected void onCreate(Bundle savedInstanceState) {
    15. super.onCreate(savedInstanceState);
    16. setContentView(R.layout.activity_main);
    17. Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
    18. R.drawable.test);
    19. //创建Palette对象
    20. Palette.generateAsync(bitmap,
    21. new Palette.PaletteAsyncListener() {
    22. @Override
    23. public void onGenerated(Palette palette) {
    24. //通过Palette来获取对应的色调
    25. Palette.Swatch vibrant =
    26. palette.getDarkVibrantSwatch();
    27. //将颜色设置给相应的组件
    28. getActionBar().setBackgroundDrawable(
    29. new ColorDrawable(vibrant.getRgb()));
    30. Window window = getWindow();
    31. window.setStatusBarColor(vibrant.getRgb());
    32. }
    33. });
    34. }
    35. }

    通过以下方法来提取不同色调的颜色。

    1. palette.getVibrantSwatch ();
    2. palette.getDarkVibrantSwatch ();
    3. palette.getLightVibrantSwatch ();
    4. palette.getMutedSwatch ();
    5. palette.getDarkMutedSwatch ();
    6. palette.getLightMutedSwatch ();

    在如上所示代码中使用getDarkVibrantSwatch()方法提取的色调效果如图12.7所示。

    12.3 Palette - 图1 图12.7 设置系统色调