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