Palette(调色板)

作者: Jinwong | 来源:发表于2016-05-14 16:37 被阅读526次

    利用Palette库来取得图片中的主要色彩

    使用这个Android的开源库android-support-v7-palette。

    • 流程:
      得到一个bitmap,通过方法进行分析,取出LightVibrantSwatch,DarkVibrantSwatch,LightMutedSwatch,DarkMutedSwatch这些样本,然后得到rgb。

    • Palette这个类中提取以下突出的颜色:
      Vibrant (有活力)
      Vibrant dark(有活力 暗色)
      Vibrant light(有活力 亮色)
      Muted (柔和)
      Muted dark(柔和 暗色)
      Muted light(柔和 亮色)

    • 创建方法

           //目标bitmap
           Bitmap bm =BitmapFactory.decodeResource(getResources(),R.drawable.kale);
           //方法1
           Palette.Builder builder = Palette.from(bm);
           Palette palette=builder.generate();
     
           //方法2   使用异步
           builder.generate(bitmap, new Palette.PaletteAsyncListener() {  
               @Override  
               public void onGenerated(Palette palette) {     
                // Here's your generated palette
           }    
    

    Palette palette=Palette.generate() 等方法直接废弃掉了

    • 使用样本(swatch)

    • 创建完一个实例之后,我们还需要得到一种采集的样本(swatch),有6中样本(swatch):
      Palette.getVibrantSwatch()
      Palette.getDarkVibrantSwatch()
      Palette.getLightVibrantSwatch()
      Palette.getMutedSwatch()
      Palette.getDarkMutedSwatch()
      Palette.getLightMutedSwatch()
      List<Palette.Swatch> swatches = palette.getSwatches();//一次性获得所有的swatch;

    • 使用方法

    getPopulation(): the amount of pixels which this swatch represents.
    getRgb(): the RGB value of this color.
    getHsl(): the HSL value of this color.
    getBodyTextColor(): the RGB value of a text color which can be displayed on top of this color.
    getTitleTextColor(): the RGB value of a text color which can be displayed on top of this color.
    

    比如如果你的TextView 有个背景图片,要想让字体颜色能够和背景图片匹配,则使用getBodyTextColor()比较合适,getTitleTextColor()其实应该和getBodyTextColor()差不多

    • Size问题
      在上面的代码中,你可能注意到了可以设置palette的size。size越大,花费的时间越长,而越小,可以选择的色彩也越小。最佳的选择是根据image的用途:
    • 头像之类的,size最好在24-32之间;
    • 风景大图之类的 size差不多在8-16;
    • 默认是16.
    • 使用代码
    Bitmap bm = BitmapFactory.decodeResource(getResources(),
                    R.drawable.kale);
            Palette palette = Palette.generate(bm);
            if (palette.getLightVibrantSwatch() != null) {//需要注意的是`getVibrantSwatch()可能会返回一个null值,所以检查一下是必须的。
                //得到不同的样本,设置给imageview进行显示
                iv.setBackgroundColor(palette.getLightVibrantSwatch().getRgb());
                iv1.setBackgroundColor(palette.getDarkVibrantSwatch().getRgb());
                iv2.setBackgroundColor(palette.getLightMutedSwatch().getRgb());
                iv3.setBackgroundColor(palette.getDarkMutedSwatch().getRgb());
    
            }
    

    相关文章

      网友评论

        本文标题:Palette(调色板)

        本文链接:https://www.haomeiwen.com/subject/uhamrttx.html