1 /*
2  * Copyright 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *       http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.support.v4.graphics;
18 
19 import android.graphics.Color;
20 import android.support.annotation.ColorInt;
21 import android.support.annotation.FloatRange;
22 import android.support.annotation.IntRange;
23 import android.support.annotation.NonNull;
24 import android.support.annotation.VisibleForTesting;
25 
26 /**
27  * A set of color-related utility methods, building upon those available in {@code Color}.
28  */
29 public final class ColorUtils {
30 
31     private static final double XYZ_WHITE_REFERENCE_X = 95.047;
32     private static final double XYZ_WHITE_REFERENCE_Y = 100;
33     private static final double XYZ_WHITE_REFERENCE_Z = 108.883;
34     private static final double XYZ_EPSILON = 0.008856;
35     private static final double XYZ_KAPPA = 903.3;
36 
37     private static final int MIN_ALPHA_SEARCH_MAX_ITERATIONS = 10;
38     private static final int MIN_ALPHA_SEARCH_PRECISION = 1;
39 
40     private static final ThreadLocal<double[]> TEMP_ARRAY = new ThreadLocal<>();
41 
ColorUtils()42     private ColorUtils() {}
43 
44     /**
45      * Composite two potentially translucent colors over each other and returns the result.
46      */
compositeColors(@olorInt int foreground, @ColorInt int background)47     public static int compositeColors(@ColorInt int foreground, @ColorInt int background) {
48         int bgAlpha = Color.alpha(background);
49         int fgAlpha = Color.alpha(foreground);
50         int a = compositeAlpha(fgAlpha, bgAlpha);
51 
52         int r = compositeComponent(Color.red(foreground), fgAlpha,
53                 Color.red(background), bgAlpha, a);
54         int g = compositeComponent(Color.green(foreground), fgAlpha,
55                 Color.green(background), bgAlpha, a);
56         int b = compositeComponent(Color.blue(foreground), fgAlpha,
57                 Color.blue(background), bgAlpha, a);
58 
59         return Color.argb(a, r, g, b);
60     }
61 
compositeAlpha(int foregroundAlpha, int backgroundAlpha)62     private static int compositeAlpha(int foregroundAlpha, int backgroundAlpha) {
63         return 0xFF - (((0xFF - backgroundAlpha) * (0xFF - foregroundAlpha)) / 0xFF);
64     }
65 
compositeComponent(int fgC, int fgA, int bgC, int bgA, int a)66     private static int compositeComponent(int fgC, int fgA, int bgC, int bgA, int a) {
67         if (a == 0) return 0;
68         return ((0xFF * fgC * fgA) + (bgC * bgA * (0xFF - fgA))) / (a * 0xFF);
69     }
70 
71     /**
72      * Returns the luminance of a color as a float between {@code 0.0} and {@code 1.0}.
73      * <p>Defined as the Y component in the XYZ representation of {@code color}.</p>
74      */
75     @FloatRange(from = 0.0, to = 1.0)
calculateLuminance(@olorInt int color)76     public static double calculateLuminance(@ColorInt int color) {
77         final double[] result = getTempDouble3Array();
78         colorToXYZ(color, result);
79         // Luminance is the Y component
80         return result[1] / 100;
81     }
82 
83     /**
84      * Returns the contrast ratio between {@code foreground} and {@code background}.
85      * {@code background} must be opaque.
86      * <p>
87      * Formula defined
88      * <a href="http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef">here</a>.
89      */
calculateContrast(@olorInt int foreground, @ColorInt int background)90     public static double calculateContrast(@ColorInt int foreground, @ColorInt int background) {
91         if (Color.alpha(background) != 255) {
92             throw new IllegalArgumentException("background can not be translucent: #"
93                     + Integer.toHexString(background));
94         }
95         if (Color.alpha(foreground) < 255) {
96             // If the foreground is translucent, composite the foreground over the background
97             foreground = compositeColors(foreground, background);
98         }
99 
100         final double luminance1 = calculateLuminance(foreground) + 0.05;
101         final double luminance2 = calculateLuminance(background) + 0.05;
102 
103         // Now return the lighter luminance divided by the darker luminance
104         return Math.max(luminance1, luminance2) / Math.min(luminance1, luminance2);
105     }
106 
107     /**
108      * Calculates the minimum alpha value which can be applied to {@code foreground} so that would
109      * have a contrast value of at least {@code minContrastRatio} when compared to
110      * {@code background}.
111      *
112      * @param foreground       the foreground color
113      * @param background       the opaque background color
114      * @param minContrastRatio the minimum contrast ratio
115      * @return the alpha value in the range 0-255, or -1 if no value could be calculated
116      */
calculateMinimumAlpha(@olorInt int foreground, @ColorInt int background, float minContrastRatio)117     public static int calculateMinimumAlpha(@ColorInt int foreground, @ColorInt int background,
118             float minContrastRatio) {
119         if (Color.alpha(background) != 255) {
120             throw new IllegalArgumentException("background can not be translucent: #"
121                     + Integer.toHexString(background));
122         }
123 
124         // First lets check that a fully opaque foreground has sufficient contrast
125         int testForeground = setAlphaComponent(foreground, 255);
126         double testRatio = calculateContrast(testForeground, background);
127         if (testRatio < minContrastRatio) {
128             // Fully opaque foreground does not have sufficient contrast, return error
129             return -1;
130         }
131 
132         // Binary search to find a value with the minimum value which provides sufficient contrast
133         int numIterations = 0;
134         int minAlpha = 0;
135         int maxAlpha = 255;
136 
137         while (numIterations <= MIN_ALPHA_SEARCH_MAX_ITERATIONS &&
138                 (maxAlpha - minAlpha) > MIN_ALPHA_SEARCH_PRECISION) {
139             final int testAlpha = (minAlpha + maxAlpha) / 2;
140 
141             testForeground = setAlphaComponent(foreground, testAlpha);
142             testRatio = calculateContrast(testForeground, background);
143 
144             if (testRatio < minContrastRatio) {
145                 minAlpha = testAlpha;
146             } else {
147                 maxAlpha = testAlpha;
148             }
149 
150             numIterations++;
151         }
152 
153         // Conservatively return the max of the range of possible alphas, which is known to pass.
154         return maxAlpha;
155     }
156 
157     /**
158      * Convert RGB components to HSL (hue-saturation-lightness).
159      * <ul>
160      * <li>outHsl[0] is Hue [0 .. 360)</li>
161      * <li>outHsl[1] is Saturation [0...1]</li>
162      * <li>outHsl[2] is Lightness [0...1]</li>
163      * </ul>
164      *
165      * @param r      red component value [0..255]
166      * @param g      green component value [0..255]
167      * @param b      blue component value [0..255]
168      * @param outHsl 3-element array which holds the resulting HSL components
169      */
RGBToHSL(@ntRangefrom = 0x0, to = 0xFF) int r, @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b, @NonNull float[] outHsl)170     public static void RGBToHSL(@IntRange(from = 0x0, to = 0xFF) int r,
171             @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b,
172             @NonNull float[] outHsl) {
173         final float rf = r / 255f;
174         final float gf = g / 255f;
175         final float bf = b / 255f;
176 
177         final float max = Math.max(rf, Math.max(gf, bf));
178         final float min = Math.min(rf, Math.min(gf, bf));
179         final float deltaMaxMin = max - min;
180 
181         float h, s;
182         float l = (max + min) / 2f;
183 
184         if (max == min) {
185             // Monochromatic
186             h = s = 0f;
187         } else {
188             if (max == rf) {
189                 h = ((gf - bf) / deltaMaxMin) % 6f;
190             } else if (max == gf) {
191                 h = ((bf - rf) / deltaMaxMin) + 2f;
192             } else {
193                 h = ((rf - gf) / deltaMaxMin) + 4f;
194             }
195 
196             s = deltaMaxMin / (1f - Math.abs(2f * l - 1f));
197         }
198 
199         h = (h * 60f) % 360f;
200         if (h < 0) {
201             h += 360f;
202         }
203 
204         outHsl[0] = constrain(h, 0f, 360f);
205         outHsl[1] = constrain(s, 0f, 1f);
206         outHsl[2] = constrain(l, 0f, 1f);
207     }
208 
209     /**
210      * Convert the ARGB color to its HSL (hue-saturation-lightness) components.
211      * <ul>
212      * <li>outHsl[0] is Hue [0 .. 360)</li>
213      * <li>outHsl[1] is Saturation [0...1]</li>
214      * <li>outHsl[2] is Lightness [0...1]</li>
215      * </ul>
216      *
217      * @param color  the ARGB color to convert. The alpha component is ignored
218      * @param outHsl 3-element array which holds the resulting HSL components
219      */
colorToHSL(@olorInt int color, @NonNull float[] outHsl)220     public static void colorToHSL(@ColorInt int color, @NonNull float[] outHsl) {
221         RGBToHSL(Color.red(color), Color.green(color), Color.blue(color), outHsl);
222     }
223 
224     /**
225      * Convert HSL (hue-saturation-lightness) components to a RGB color.
226      * <ul>
227      * <li>hsl[0] is Hue [0 .. 360)</li>
228      * <li>hsl[1] is Saturation [0...1]</li>
229      * <li>hsl[2] is Lightness [0...1]</li>
230      * </ul>
231      * If hsv values are out of range, they are pinned.
232      *
233      * @param hsl 3-element array which holds the input HSL components
234      * @return the resulting RGB color
235      */
236     @ColorInt
HSLToColor(@onNull float[] hsl)237     public static int HSLToColor(@NonNull float[] hsl) {
238         final float h = hsl[0];
239         final float s = hsl[1];
240         final float l = hsl[2];
241 
242         final float c = (1f - Math.abs(2 * l - 1f)) * s;
243         final float m = l - 0.5f * c;
244         final float x = c * (1f - Math.abs((h / 60f % 2f) - 1f));
245 
246         final int hueSegment = (int) h / 60;
247 
248         int r = 0, g = 0, b = 0;
249 
250         switch (hueSegment) {
251             case 0:
252                 r = Math.round(255 * (c + m));
253                 g = Math.round(255 * (x + m));
254                 b = Math.round(255 * m);
255                 break;
256             case 1:
257                 r = Math.round(255 * (x + m));
258                 g = Math.round(255 * (c + m));
259                 b = Math.round(255 * m);
260                 break;
261             case 2:
262                 r = Math.round(255 * m);
263                 g = Math.round(255 * (c + m));
264                 b = Math.round(255 * (x + m));
265                 break;
266             case 3:
267                 r = Math.round(255 * m);
268                 g = Math.round(255 * (x + m));
269                 b = Math.round(255 * (c + m));
270                 break;
271             case 4:
272                 r = Math.round(255 * (x + m));
273                 g = Math.round(255 * m);
274                 b = Math.round(255 * (c + m));
275                 break;
276             case 5:
277             case 6:
278                 r = Math.round(255 * (c + m));
279                 g = Math.round(255 * m);
280                 b = Math.round(255 * (x + m));
281                 break;
282         }
283 
284         r = constrain(r, 0, 255);
285         g = constrain(g, 0, 255);
286         b = constrain(b, 0, 255);
287 
288         return Color.rgb(r, g, b);
289     }
290 
291     /**
292      * Set the alpha component of {@code color} to be {@code alpha}.
293      */
294     @ColorInt
setAlphaComponent(@olorInt int color, @IntRange(from = 0x0, to = 0xFF) int alpha)295     public static int setAlphaComponent(@ColorInt int color,
296             @IntRange(from = 0x0, to = 0xFF) int alpha) {
297         if (alpha < 0 || alpha > 255) {
298             throw new IllegalArgumentException("alpha must be between 0 and 255.");
299         }
300         return (color & 0x00ffffff) | (alpha << 24);
301     }
302 
303     /**
304      * Convert the ARGB color to its CIE Lab representative components.
305      *
306      * @param color  the ARGB color to convert. The alpha component is ignored
307      * @param outLab 3-element array which holds the resulting LAB components
308      */
colorToLAB(@olorInt int color, @NonNull double[] outLab)309     public static void colorToLAB(@ColorInt int color, @NonNull double[] outLab) {
310         RGBToLAB(Color.red(color), Color.green(color), Color.blue(color), outLab);
311     }
312 
313     /**
314      * Convert RGB components to its CIE Lab representative components.
315      *
316      * <ul>
317      * <li>outLab[0] is L [0 ...1)</li>
318      * <li>outLab[1] is a [-128...127)</li>
319      * <li>outLab[2] is b [-128...127)</li>
320      * </ul>
321      *
322      * @param r      red component value [0..255]
323      * @param g      green component value [0..255]
324      * @param b      blue component value [0..255]
325      * @param outLab 3-element array which holds the resulting LAB components
326      */
RGBToLAB(@ntRangefrom = 0x0, to = 0xFF) int r, @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b, @NonNull double[] outLab)327     public static void RGBToLAB(@IntRange(from = 0x0, to = 0xFF) int r,
328             @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b,
329             @NonNull double[] outLab) {
330         // First we convert RGB to XYZ
331         RGBToXYZ(r, g, b, outLab);
332         // outLab now contains XYZ
333         XYZToLAB(outLab[0], outLab[1], outLab[2], outLab);
334         // outLab now contains LAB representation
335     }
336 
337     /**
338      * Convert the ARGB color to it's CIE XYZ representative components.
339      *
340      * <p>The resulting XYZ representation will use the D65 illuminant and the CIE
341      * 2° Standard Observer (1931).</p>
342      *
343      * <ul>
344      * <li>outXyz[0] is X [0 ...95.047)</li>
345      * <li>outXyz[1] is Y [0...100)</li>
346      * <li>outXyz[2] is Z [0...108.883)</li>
347      * </ul>
348      *
349      * @param color  the ARGB color to convert. The alpha component is ignored
350      * @param outXyz 3-element array which holds the resulting LAB components
351      */
colorToXYZ(@olorInt int color, @NonNull double[] outXyz)352     public static void colorToXYZ(@ColorInt int color, @NonNull double[] outXyz) {
353         RGBToXYZ(Color.red(color), Color.green(color), Color.blue(color), outXyz);
354     }
355 
356     /**
357      * Convert RGB components to it's CIE XYZ representative components.
358      *
359      * <p>The resulting XYZ representation will use the D65 illuminant and the CIE
360      * 2° Standard Observer (1931).</p>
361      *
362      * <ul>
363      * <li>outXyz[0] is X [0 ...95.047)</li>
364      * <li>outXyz[1] is Y [0...100)</li>
365      * <li>outXyz[2] is Z [0...108.883)</li>
366      * </ul>
367      *
368      * @param r      red component value [0..255]
369      * @param g      green component value [0..255]
370      * @param b      blue component value [0..255]
371      * @param outXyz 3-element array which holds the resulting XYZ components
372      */
RGBToXYZ(@ntRangefrom = 0x0, to = 0xFF) int r, @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b, @NonNull double[] outXyz)373     public static void RGBToXYZ(@IntRange(from = 0x0, to = 0xFF) int r,
374             @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b,
375             @NonNull double[] outXyz) {
376         if (outXyz.length != 3) {
377             throw new IllegalArgumentException("outXyz must have a length of 3.");
378         }
379 
380         double sr = r / 255.0;
381         sr = sr < 0.04045 ? sr / 12.92 : Math.pow((sr + 0.055) / 1.055, 2.4);
382         double sg = g / 255.0;
383         sg = sg < 0.04045 ? sg / 12.92 : Math.pow((sg + 0.055) / 1.055, 2.4);
384         double sb = b / 255.0;
385         sb = sb < 0.04045 ? sb / 12.92 : Math.pow((sb + 0.055) / 1.055, 2.4);
386 
387         outXyz[0] = 100 * (sr * 0.4124 + sg * 0.3576 + sb * 0.1805);
388         outXyz[1] = 100 * (sr * 0.2126 + sg * 0.7152 + sb * 0.0722);
389         outXyz[2] = 100 * (sr * 0.0193 + sg * 0.1192 + sb * 0.9505);
390     }
391 
392     /**
393      * Converts a color from CIE XYZ to CIE Lab representation.
394      *
395      * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE
396      * 2° Standard Observer (1931).</p>
397      *
398      * <ul>
399      * <li>outLab[0] is L [0 ...1)</li>
400      * <li>outLab[1] is a [-128...127)</li>
401      * <li>outLab[2] is b [-128...127)</li>
402      * </ul>
403      *
404      * @param x      X component value [0...95.047)
405      * @param y      Y component value [0...100)
406      * @param z      Z component value [0...108.883)
407      * @param outLab 3-element array which holds the resulting Lab components
408      */
409     public static void XYZToLAB(@FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_X) double x,
410             @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Y) double y,
411             @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Z) double z,
412             @NonNull double[] outLab) {
413         if (outLab.length != 3) {
414             throw new IllegalArgumentException("outLab must have a length of 3.");
415         }
416         x = pivotXyzComponent(x / XYZ_WHITE_REFERENCE_X);
417         y = pivotXyzComponent(y / XYZ_WHITE_REFERENCE_Y);
418         z = pivotXyzComponent(z / XYZ_WHITE_REFERENCE_Z);
419         outLab[0] = Math.max(0, 116 * y - 16);
420         outLab[1] = 500 * (x - y);
421         outLab[2] = 200 * (y - z);
422     }
423 
424     /**
425      * Converts a color from CIE Lab to CIE XYZ representation.
426      *
427      * <p>The resulting XYZ representation will use the D65 illuminant and the CIE
428      * 2° Standard Observer (1931).</p>
429      *
430      * <ul>
431      * <li>outXyz[0] is X [0 ...95.047)</li>
432      * <li>outXyz[1] is Y [0...100)</li>
433      * <li>outXyz[2] is Z [0...108.883)</li>
434      * </ul>
435      *
436      * @param l      L component value [0...100)
437      * @param a      A component value [-128...127)
438      * @param b      B component value [-128...127)
439      * @param outXyz 3-element array which holds the resulting XYZ components
440      */
441     public static void LABToXYZ(@FloatRange(from = 0f, to = 100) final double l,
442             @FloatRange(from = -128, to = 127) final double a,
443             @FloatRange(from = -128, to = 127) final double b,
444             @NonNull double[] outXyz) {
445         final double fy = (l + 16) / 116;
446         final double fx = a / 500 + fy;
447         final double fz = fy - b / 200;
448 
449         double tmp = Math.pow(fx, 3);
450         final double xr = tmp > XYZ_EPSILON ? tmp : (116 * fx - 16) / XYZ_KAPPA;
451         final double yr = l > XYZ_KAPPA * XYZ_EPSILON ? Math.pow(fy, 3) : l / XYZ_KAPPA;
452 
453         tmp = Math.pow(fz, 3);
454         final double zr = tmp > XYZ_EPSILON ? tmp : (116 * fz - 16) / XYZ_KAPPA;
455 
456         outXyz[0] = xr * XYZ_WHITE_REFERENCE_X;
457         outXyz[1] = yr * XYZ_WHITE_REFERENCE_Y;
458         outXyz[2] = zr * XYZ_WHITE_REFERENCE_Z;
459     }
460 
461     /**
462      * Converts a color from CIE XYZ to its RGB representation.
463      *
464      * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE
465      * 2° Standard Observer (1931).</p>
466      *
467      * @param x X component value [0...95.047)
468      * @param y Y component value [0...100)
469      * @param z Z component value [0...108.883)
470      * @return int containing the RGB representation
471      */
472     @ColorInt
XYZToColor(@loatRangefrom = 0f, to = XYZ_WHITE_REFERENCE_X) double x, @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Y) double y, @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Z) double z)473     public static int XYZToColor(@FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_X) double x,
474             @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Y) double y,
475             @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Z) double z) {
476         double r = (x * 3.2406 + y * -1.5372 + z * -0.4986) / 100;
477         double g = (x * -0.9689 + y * 1.8758 + z * 0.0415) / 100;
478         double b = (x * 0.0557 + y * -0.2040 + z * 1.0570) / 100;
479 
480         r = r > 0.0031308 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : 12.92 * r;
481         g = g > 0.0031308 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : 12.92 * g;
482         b = b > 0.0031308 ? 1.055 * Math.pow(b, 1 / 2.4) - 0.055 : 12.92 * b;
483 
484         return Color.rgb(
485                 constrain((int) Math.round(r * 255), 0, 255),
486                 constrain((int) Math.round(g * 255), 0, 255),
487                 constrain((int) Math.round(b * 255), 0, 255));
488     }
489 
490     /**
491      * Converts a color from CIE Lab to its RGB representation.
492      *
493      * @param l L component value [0...100]
494      * @param a A component value [-128...127]
495      * @param b B component value [-128...127]
496      * @return int containing the RGB representation
497      */
498     @ColorInt
LABToColor(@loatRangefrom = 0f, to = 100) final double l, @FloatRange(from = -128, to = 127) final double a, @FloatRange(from = -128, to = 127) final double b)499     public static int LABToColor(@FloatRange(from = 0f, to = 100) final double l,
500             @FloatRange(from = -128, to = 127) final double a,
501             @FloatRange(from = -128, to = 127) final double b) {
502         final double[] result = getTempDouble3Array();
503         LABToXYZ(l, a, b, result);
504         return XYZToColor(result[0], result[1], result[2]);
505     }
506 
507     /**
508      * Returns the euclidean distance between two LAB colors.
509      */
distanceEuclidean(@onNull double[] labX, @NonNull double[] labY)510     public static double distanceEuclidean(@NonNull double[] labX, @NonNull double[] labY) {
511         return Math.sqrt(Math.pow(labX[0] - labY[0], 2)
512                 + Math.pow(labX[1] - labY[1], 2)
513                 + Math.pow(labX[2] - labY[2], 2));
514     }
515 
constrain(float amount, float low, float high)516     private static float constrain(float amount, float low, float high) {
517         return amount < low ? low : (amount > high ? high : amount);
518     }
519 
constrain(int amount, int low, int high)520     private static int constrain(int amount, int low, int high) {
521         return amount < low ? low : (amount > high ? high : amount);
522     }
523 
pivotXyzComponent(double component)524     private static double pivotXyzComponent(double component) {
525         return component > XYZ_EPSILON
526                 ? Math.pow(component, 1 / 3.0)
527                 : (XYZ_KAPPA * component + 16) / 116;
528     }
529 
530     /**
531      * Blend between two ARGB colors using the given ratio.
532      *
533      * <p>A blend ratio of 0.0 will result in {@code color1}, 0.5 will give an even blend,
534      * 1.0 will result in {@code color2}.</p>
535      *
536      * @param color1 the first ARGB color
537      * @param color2 the second ARGB color
538      * @param ratio  the blend ratio of {@code color1} to {@code color2}
539      */
540     @ColorInt
blendARGB(@olorInt int color1, @ColorInt int color2, @FloatRange(from = 0.0, to = 1.0) float ratio)541     public static int blendARGB(@ColorInt int color1, @ColorInt int color2,
542             @FloatRange(from = 0.0, to = 1.0) float ratio) {
543         final float inverseRatio = 1 - ratio;
544         float a = Color.alpha(color1) * inverseRatio + Color.alpha(color2) * ratio;
545         float r = Color.red(color1) * inverseRatio + Color.red(color2) * ratio;
546         float g = Color.green(color1) * inverseRatio + Color.green(color2) * ratio;
547         float b = Color.blue(color1) * inverseRatio + Color.blue(color2) * ratio;
548         return Color.argb((int) a, (int) r, (int) g, (int) b);
549     }
550 
551     /**
552      * Blend between {@code hsl1} and {@code hsl2} using the given ratio. This will interpolate
553      * the hue using the shortest angle.
554      *
555      * <p>A blend ratio of 0.0 will result in {@code hsl1}, 0.5 will give an even blend,
556      * 1.0 will result in {@code hsl2}.</p>
557      *
558      * @param hsl1      3-element array which holds the first HSL color
559      * @param hsl2      3-element array which holds the second HSL color
560      * @param ratio     the blend ratio of {@code hsl1} to {@code hsl2}
561      * @param outResult 3-element array which holds the resulting HSL components
562      */
blendHSL(@onNull float[] hsl1, @NonNull float[] hsl2, @FloatRange(from = 0.0, to = 1.0) float ratio, @NonNull float[] outResult)563     public static void blendHSL(@NonNull float[] hsl1, @NonNull float[] hsl2,
564             @FloatRange(from = 0.0, to = 1.0) float ratio, @NonNull float[] outResult) {
565         if (outResult.length != 3) {
566             throw new IllegalArgumentException("result must have a length of 3.");
567         }
568         final float inverseRatio = 1 - ratio;
569         // Since hue is circular we will need to interpolate carefully
570         outResult[0] = circularInterpolate(hsl1[0], hsl2[0], ratio);
571         outResult[1] = hsl1[1] * inverseRatio + hsl2[1] * ratio;
572         outResult[2] = hsl1[2] * inverseRatio + hsl2[2] * ratio;
573     }
574 
575     /**
576      * Blend between two CIE-LAB colors using the given ratio.
577      *
578      * <p>A blend ratio of 0.0 will result in {@code lab1}, 0.5 will give an even blend,
579      * 1.0 will result in {@code lab2}.</p>
580      *
581      * @param lab1      3-element array which holds the first LAB color
582      * @param lab2      3-element array which holds the second LAB color
583      * @param ratio     the blend ratio of {@code lab1} to {@code lab2}
584      * @param outResult 3-element array which holds the resulting LAB components
585      */
blendLAB(@onNull double[] lab1, @NonNull double[] lab2, @FloatRange(from = 0.0, to = 1.0) double ratio, @NonNull double[] outResult)586     public static void blendLAB(@NonNull double[] lab1, @NonNull double[] lab2,
587             @FloatRange(from = 0.0, to = 1.0) double ratio, @NonNull double[] outResult) {
588         if (outResult.length != 3) {
589             throw new IllegalArgumentException("outResult must have a length of 3.");
590         }
591         final double inverseRatio = 1 - ratio;
592         outResult[0] = lab1[0] * inverseRatio + lab2[0] * ratio;
593         outResult[1] = lab1[1] * inverseRatio + lab2[1] * ratio;
594         outResult[2] = lab1[2] * inverseRatio + lab2[2] * ratio;
595     }
596 
597     @VisibleForTesting
circularInterpolate(float a, float b, float f)598     static float circularInterpolate(float a, float b, float f) {
599         if (Math.abs(b - a) > 180) {
600             if (b > a) {
601                 a += 360;
602             } else {
603                 b += 360;
604             }
605         }
606         return (a + ((b - a) * f)) % 360;
607     }
608 
getTempDouble3Array()609     private static double[] getTempDouble3Array() {
610         double[] result = TEMP_ARRAY.get();
611         if (result == null) {
612             result = new double[3];
613             TEMP_ARRAY.set(result);
614         }
615         return result;
616     }
617 
618 }
619