如何使用Palette提取Bitmap的顏色


5.X提出了color palette 的概念,能夠讓主題動態的去適應當前的頁面色調,讓整個app色調看起來比較和諧統一

那么如何使用Palette呢,必不可少,我們需要在Android studio中引用相關的jar包,我使用的jar是

 compile 'com.android.support:palette-v7:21.0.0'

第一:主要是通過傳遞一個Bitmap對象給Palette,我們可以使用Paltte下的方法,靜態的方法Paltte.generate()或者Paltte.generateAsync(),我們可以看下源碼

//generate(Bitmap) 生成含有16種顏色種類的Palette;
    public static Palette generate(Bitmap bitmap) {
        return generate(bitmap, DEFAULT_CALCULATE_NUMBER_COLORS);
    }
//generate(Bitmap, int) 生成含有指定數量顏色種類的Palette,數量越多需要的時間越久。
    public static Palette generate(Bitmap bitmap, int numColors) {
        checkBitmapParam(bitmap);
        checkNumberColorsParam(numColors);
        // First we'll scale down the bitmap so it's shortest dimension is 100px
        final Bitmap scaledBitmap = scaleBitmapDown(bitmap);
        // Now generate a quantizer from the Bitmap
        ColorCutQuantizer quantizer = ColorCutQuantizer.fromBitmap(scaledBitmap, numColors);
        // If created a new bitmap, recycle it
        if (scaledBitmap != bitmap) {
            scaledBitmap.recycle();
        }
        // Now return a ColorExtractor instance
        return new Palette(quantizer.getQuantizedColors());
    }
    public static AsyncTask<Bitmap, Void, Palette> generateAsync(
            Bitmap bitmap, PaletteAsyncListener listener) {
        return generateAsync(bitmap, DEFAULT_CALCULATE_NUMBER_COLORS, listener);
    }
    public static AsyncTask<Bitmap, Void, Palette> generateAsync(
            final Bitmap bitmap, final int numColors, final PaletteAsyncListener listener) {
        checkBitmapParam(bitmap);
        checkNumberColorsParam(numColors);
        checkAsyncListenerParam(listener);

        return AsyncTaskCompat.executeParallel(
                new AsyncTask<Bitmap, Void, Palette>() {
                    @Override
                    protected Palette doInBackground(Bitmap... params) {
                        return generate(params[0], numColors);
                    }

                    @Override
                    protected void onPostExecute(Palette colorExtractor) {
                        listener.onGenerated(colorExtractor);
                    }
                }, bitmap);
    }

 

2. 由於Android 對bitmap的操作可能是好事操作,我們可以選擇使用Palette.generateAsync()的方法.他比Palette.generate()的區別就是需要傳入PaletteAsyncListener

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView mIv=(ImageView)findViewById(R.id.iv );

        Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.mipmap.splash);
        mIv.setImageBitmap(bitmap);
        Palette.generateAsync(bitmap,new Palette.PaletteAsyncListener(){

            @Override
            public void onGenerated(Palette palette) {
                //通過palette來獲取對應的色調
                Palette.Swatch vibrant=palette.getLightVibrantSwatch();
                //int vibrant=palette.getMutedColor(990000);
                //將顏色設置給相應的組件,比如actionbar,狀態欄
                getActionBar().setBackgroundDrawable(new ColorDrawable(vibrant.getRgb()));
                //getActionBar().setBackgroundDrawable(new ColorDrawable(vibrant));
                Window window =getWindow();
                window.setStatusBarColor(vibrant.getRgb());
               // window.setStatusBarColor(vibrant);
            }
        });
    }

3.Palette默認情況會解析出來16種顏色,但是我們常用的無非就6種:

//獲取鮮艷的顏色
    public int getVibrantColor(int defaultColor) {
        return mVibrantSwatch != null ? mVibrantSwatch.getRgb() : defaultColor;
    }
//獲取鮮艷顏色中的亮顏色 public int getLightVibrantColor(int defaultColor) { return mLightVibrantSwatch != null ? mLightVibrantSwatch.getRgb() : defaultColor; }
//獲取鮮艷顏色中的暗色
public int getDarkVibrantColor(int defaultColor) { return mDarkVibrantSwatch != null ? mDarkVibrantSwatch.getRgb() : defaultColor; }
//獲取柔和的顏色
public int getMutedColor(int defaultColor) { return mMutedSwatch != null ? mMutedSwatch.getRgb() : defaultColor; }
//獲取柔和色中的亮顏色
public int getLightMutedColor(int defaultColor) { return mLightMutedColor != null ? mLightMutedColor.getRgb() : defaultColor; }
//獲取柔和顏色中的暗色
public int getDarkMutedColor(int defaultColor) { return mDarkMutedSwatch != null ? mDarkMutedSwatch.getRgb() : defaultColor; }

我們看下效果圖:

上圖1部分代碼表示:
Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.mipmap.banner_pingan_default); mIv.setImageBitmap(bitmap); Palette palette = Palette.generate(bitmap); int vibrant = palette.getVibrantColor(990000);//個人試了一下,好像這個顏色數字沒多大用。。。。 int vibrantLight = palette.getLightVibrantColor(990000); int vibrantDark = palette.getDarkVibrantColor(990000); int muted = palette.getMutedColor(990000); int mutedLight = palette.getLightMutedColor(990000); int mutedDark = palette.getDarkMutedColor(990000);
上圖2部分代碼表示: Palette.generateAsync(bitmap,
new Palette.PaletteAsyncListener(){ @Override public void onGenerated(Palette palette) { //通過palette來獲取對應的色調 Palette.Swatch vibrant=palette.getLightVibrantSwatch(); //int vibrant=palette.getMutedColor(990000); //將顏色設置給相應的組件 getActionBar().setBackgroundDrawable(new ColorDrawable(vibrant.getRgb())); //getActionBar().setBackgroundDrawable(new ColorDrawable(vibrant)); Window window =getWindow(); window.setStatusBarColor(vibrant.getRgb()); // window.setStatusBarColor(vibrant); } }); }

4.Palette獲取相應的顏色另一種方式 使用swatch:palette解析來的顏色都有對應swatch,它里面包含了很多顏色信息,常用的獲取顏色有以下幾幾種

    public Swatch getVibrantSwatch() {
        return mVibrantSwatch;
    }

    /**
     * Returns a light and vibrant swatch from the palette. Might be null.
     */
    public Swatch getLightVibrantSwatch() {
        return mLightVibrantSwatch;
    }

    /**
     * Returns a dark and vibrant swatch from the palette. Might be null.
     */
    public Swatch getDarkVibrantSwatch() {
        return mDarkVibrantSwatch;
    }

    /**
     * Returns a muted swatch from the palette. Might be null.
     */
    public Swatch getMutedSwatch() {
        return mMutedSwatch;
    }

    /**
     * Returns a muted and light swatch from the palette. Might be null.
     */
    public Swatch getLightMutedSwatch() {
        return mLightMutedColor;
    }

    /**
     * Returns a muted and dark swatch from the palette. Might be null.
     */
    public Swatch getDarkMutedSwatch() {
        return mDarkMutedSwatch;
    }

你可以從Swatch里面獲取你需要的顏色信息,比如RGB顏色值、HSL顏色向量、對應顏色在圖像中所占的比例、與對應顏色搭配的標題字體顏色和正文字體顏色。

Palette palette  = Palette.generate(bitmap);
Palette.Swatch swatch = palette.getVibrantSwatch();
//hsl顏色向量
float[] hslValues = swatch.getHsl();
//rgb顏色值
int rgbColor = swatch.getRgb();
//該顏色在圖像中所占的像素數
int pixelCount = swatch.getPopulation();
//對應的標題字體顏色
int titleTextColor = swatch.getTitleTextColor();
//對應的正文字體顏色
int bodyTextColor = swatch.getBodyTextColor();

在這里要注意的是,如果想要使用swatch獲取的顏色,不能像上面直接使用get方法,他不需要傳入默認的顏色值,如下例子:

通過palette來獲取對應的色調
Palette.Swatch vibrant=palette.getLightVibrantSwatch();

 不知道大家有沒有注意到源碼中這一句話,他的意思說如果Palette沒有解析到swatch的話,就會返回一個null。

 /**
   * Returns a light and vibrant swatch from the palette. Might be null.
   */

5.在源碼中還有這樣一個方法:獲取所有的顏色(16種),返回的是一個list集合

 
         
/**
* Returns all of the swatches which make up the palette.
*/
public List<Swatch> getSwatches() {
return Collections.unmodifiableList(mSwatches);
}

 效果圖:

代碼實現:

 List<Palette.Swatch> swatchs=Palette.generate(bitmap).getSwatches();
        for (int i=0;i<swatchs.size();i++){
            View view = new View(MainActivity.this);
            view.setBackgroundColor(swatchs.get(i).getRgb());
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,50));
            mLinearLayout.addView(view);
        }

 

 

 

  

  

 
        

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM