Android L Palette Implementation principle

Source: Internet
Author: User

Sometimes, see some of the interface color, mood may be very comfortable, sometimes, see some other colors, feel very annoying, uncomfortable, see the Android L Palette from the picture to extract the color of the screen, feel pretty good, go to understand the next Palette palette.

Read the code, according to my understanding, probably say the main steps:

The first step, the picture is reduced, and then the whole process, you can reduce the computational capacity and reduce the use of memory, and do not shrink to achieve the same effect

/** * Scale the bitmap off so that     it's smallest dimension is     * {@value #CALCULATE_BITMAP_MIN_DIMENSION}px. If {@code bitmap} is smaller than this, than it is     returned.     */    private static Bitmap Scalebitmapdown (Bitmap Bitmap) {        final int mindimension = Math.min (Bitmap.getwidth (), Bitmap.getheight ());        if (mindimension <= calculate_bitmap_min_dimension) {            //If the BITMAP is small enough already, just return it            return bitmap;        }        Final float Scaleratio = calculate_bitmap_min_dimension/(float) mindimension;        Return Bitmap.createscaledbitmap (Bitmap,                Math.Round (Bitmap.getwidth () * scaleratio),                Math.Round ( Bitmap.getheight () * scaleratio),                false);    }


The second step, the reduced image data, placed in an int array

/**     * Factory-method to generate a {@link Colorcutquantizer} from a {@link Bitmap} object.     *     * @param bitmap bitmap To extract the pixel data from     * @param maxcolors The maximum number of colors that Shoul D is in the result palette.     *    /static Colorcutquantizer Frombitmap (Bitmap Bitmap, int maxcolors) {        final int width = bitmap.getwidth ();        Final int height = bitmap.getheight ();        Final int[] pixels = new int[width * height];        Bitmap.getpixels (pixels, 0, width, 0, 0, width, height);        return new Colorcutquantizer (new Colorhistogram (pixels), maxcolors);    


The third step, the int array from small to large sort, the equivalent of a picture of the same color stacked together, and then calculate the total number of colors, each color it is how big, these are in a called colorhistogram (color histogram) class inside the calculation, with color histograms, is how many column colors, how high is the color of each column


/** * Class which provides a histogram for RGB values.    */final class Colorhistogram {private final int[] mcolors;    Private final int[] mcolorcounts;    private final int mnumbercolors;     /** * A new {@link Colorhistogram} instance. * * @param pixels array of image contents */Colorhistogram (final int[] pixels) {//Sort the pixels to        Enable counting below arrays.sort (pixels);        Count number of distinct colors mnumbercolors = countdistinctcolors (pixels);        Create Arrays mcolors = new Int[mnumbercolors];        mcolorcounts = new Int[mnumbercolors];    Finally count the frequency of each color countfrequencies (pixels);     }/** * @return gets how many bars are in different colors number of distinct colors in the image.    */int getnumberofcolors () {return mnumbercolors;     }/** * @return gets the array of different colors after the sequence an array containing all of the distinct colors in the image. */int[] Getcolors () {return mColors;     }/** * @return Gets the array of how high each bar is saved an array containing the frequency of a distinct colors within the image.    */int[] Getcolorcounts () {return mcolorcounts;            }//Calculate how many bars are in different colors private static int countdistinctcolors (final int[] pixels) {if (Pixels.length < 2) {        If we have less than 2 pixels we can stop the here return pixels.length;        }//If We have at least 2 pixels and we have a minimum of 1 color ... int colorcount = 1;        int currentcolor = pixels[0]; Now iterate from the second pixel to the end, counting distinct colors for (int i = 1; i < pixels.length; i++                ) {//If we encounter a new color, increase the population If (pixels[i]! = CurrentColor) {                CurrentColor = Pixels[i];            colorcount++;    }} return colorcount; }//Calculate how high private void countfrequencies (final int[] pixels) {if (pixels) for each bar. length = = 0) {return;        } int currentcolorindex = 0;        int currentcolor = pixels[0];        Mcolors[currentcolorindex] = CurrentColor;        Mcolorcounts[currentcolorindex] = 1;               LOG.I ("Pixels.length", "" "+ pixels.length);        if (pixels.length = = 1) {//If we are only having one pixel, we can stop here return; }//Now iterate from the second pixel to the end, population distinct colors for (int i = 1; i < Pixels.length; i++) {if (pixels[i] = = CurrentColor) {//We ' ve hit the same color as before, increase Populati            On mcolorcounts[currentcolorindex]++;                } else {//We ' ve hit a new color, increase index currentcolor = pixels[i];                currentcolorindex++;                Mcolors[currentcolorindex] = CurrentColor;            Mcolorcounts[currentcolorindex] = 1; }        }    }}

The fourth step, will be a variety of colors, according to the RGB-HSL algorithm, the corresponding HSL (H:hue hue,s:saturation saturation L lightness luminosity ), according to specific conditions, For example, whether the brightness L is close to white, black, and a judgment called Isnearrediline, the explanation is @return True if the color lies close to the red side of the "I line" near the red private area? )., and then according to these three conditions, filter out these colors, what is the HSL and RGB-to-HSL algorithm can see the next encyclopedia, more detailed description


 /** * Private constructor. * * @param colorhistogram histogram representing an image ' s pixel data * @param maxcolors The maximum number of CO     Lors that should is in the result palette. */Private Colorcutquantizer (Colorhistogram colorhistogram, int maxcolors) {final int rawcolorcount = Colorhist        Ogram.getnumberofcolors (); Final int[] rawcolors = Colorhistogram.getcolors ();//color array final int[] rawcolorcounts = Colorhistogram.getcolorcount        s ();//corresponds to rawcolors each color array size//First, lets pack the populations into a sparseintarray so that they can be easily        Retrieved without knowing a color ' s index mcolorpopulations = new Sparseintarray (rawcolorcount);        for (int i = 0; i < rawcolors.length; i++) {mcolorpopulations.append (rawcolors[i], rawcolorcounts[i]); }//Now go through all of the colors and keep those which we don't want to ignore mcolors = new Int[ra        Wcolorcount]; int ValidcolOrcount = 0; for (int color:rawcolors) {if (!shouldignorecolor (color)) {mcolors[validcolorcount++] = Colo            R        }} log.d ("Mcolors Length", "" +mcolors.length);  if (Validcolorcount <= maxcolors) {//The image has fewer colors than the maximum requested, so just return                       The colors mquantizedcolors = new arraylist<swatch> ();            for (final int color:mcolors) {Mquantizedcolors.add (new Swatch (color, mcolorpopulations.get (color))); }} else {//We need use quantization to reduce the number of colors Mquantizedcol        ORS = Quantizepixels (validColorCount-1, maxcolors); }    }
<span style= "Font-weight:bold;" ></span>
<span style= "Font-weight:bold;" > Cut a picture here to see </span>


The fifth step, according to a variety of brightness, saturation of the range, such as vibrant dark color, vibrant bright colors, soft color, soft dark color, soft bright colors, find the corresponding color

Private Swatch Findcolor (float Targetluma, float minluma, float maxluma, float targetsaturatio        N, float minsaturation, float maxsaturation) {Swatch max = null;        float maxValue = 0f;            for (Swatch swatch:mswatches) {final float Sat = SWATCH.GETHSL () [1];            Final float Luma = SWATCH.GETHSL () [2];  if (Sat >= minsaturation && Sat <= maxsaturation && luma >= Minluma && Luma <= Maxluma &&!isalreadyselected (swatch)) {Float Thisvalue = createcom                Parisonvalue (Sat, targetsaturation, Luma, Targetluma, Swatch.getpopulation (), mhighestpopulation);                    if (max = = NULL | | thisvalue > MaxValue) {max = swatch;                MaxValue = Thisvalue;    }}}} return max; }

Look down.



full code download (compatible with low version, Viewpager for "Infinite Loop" and imageview for reuse year-end package )

Welcome reprint, but please indicate the source http://blog.csdn.net/yebo0505/article/details/43234113

Android L Palette Implementation principle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.