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