• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 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.util;
18 
19 import android.annotation.ColorInt;
20 import android.annotation.FloatRange;
21 import android.annotation.IntRange;
22 import android.annotation.NonNull;
23 import android.app.Notification;
24 import android.content.Context;
25 import android.content.res.ColorStateList;
26 import android.content.res.Resources;
27 import android.graphics.Bitmap;
28 import android.graphics.Color;
29 import android.graphics.drawable.AnimationDrawable;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.graphics.drawable.Icon;
33 import android.graphics.drawable.VectorDrawable;
34 import android.text.SpannableStringBuilder;
35 import android.text.Spanned;
36 import android.text.style.BackgroundColorSpan;
37 import android.text.style.CharacterStyle;
38 import android.text.style.ForegroundColorSpan;
39 import android.text.style.TextAppearanceSpan;
40 import android.util.Log;
41 import android.util.Pair;
42 
43 import java.util.Arrays;
44 import java.util.WeakHashMap;
45 
46 /**
47  * Helper class to process legacy (Holo) notifications to make them look like material notifications.
48  *
49  * @hide
50  */
51 public class NotificationColorUtil {
52 
53     private static final String TAG = "NotificationColorUtil";
54     private static final boolean DEBUG = false;
55 
56     private static final Object sLock = new Object();
57     private static NotificationColorUtil sInstance;
58 
59     private final ImageUtils mImageUtils = new ImageUtils();
60     private final WeakHashMap<Bitmap, Pair<Boolean, Integer>> mGrayscaleBitmapCache =
61             new WeakHashMap<Bitmap, Pair<Boolean, Integer>>();
62 
63     private final int mGrayscaleIconMaxSize; // @dimen/notification_large_icon_width (64dp)
64 
getInstance(Context context)65     public static NotificationColorUtil getInstance(Context context) {
66         synchronized (sLock) {
67             if (sInstance == null) {
68                 sInstance = new NotificationColorUtil(context);
69             }
70             return sInstance;
71         }
72     }
73 
NotificationColorUtil(Context context)74     private NotificationColorUtil(Context context) {
75         mGrayscaleIconMaxSize = context.getResources().getDimensionPixelSize(
76                 com.android.internal.R.dimen.notification_large_icon_width);
77     }
78 
79     /**
80      * Checks whether a Bitmap is a small grayscale icon.
81      * Grayscale here means "very close to a perfect gray"; icon means "no larger than 64dp".
82      *
83      * @param bitmap The bitmap to test.
84      * @return True if the bitmap is grayscale; false if it is color or too large to examine.
85      */
isGrayscaleIcon(Bitmap bitmap)86     public boolean isGrayscaleIcon(Bitmap bitmap) {
87         // quick test: reject large bitmaps
88         if (bitmap.getWidth() > mGrayscaleIconMaxSize
89                 || bitmap.getHeight() > mGrayscaleIconMaxSize) {
90             return false;
91         }
92 
93         synchronized (sLock) {
94             Pair<Boolean, Integer> cached = mGrayscaleBitmapCache.get(bitmap);
95             if (cached != null) {
96                 if (cached.second == bitmap.getGenerationId()) {
97                     return cached.first;
98                 }
99             }
100         }
101         boolean result;
102         int generationId;
103         synchronized (mImageUtils) {
104             result = mImageUtils.isGrayscale(bitmap);
105 
106             // generationId and the check whether the Bitmap is grayscale can't be read atomically
107             // here. However, since the thread is in the process of posting the notification, we can
108             // assume that it doesn't modify the bitmap while we are checking the pixels.
109             generationId = bitmap.getGenerationId();
110         }
111         synchronized (sLock) {
112             mGrayscaleBitmapCache.put(bitmap, Pair.create(result, generationId));
113         }
114         return result;
115     }
116 
117     /**
118      * Checks whether a Drawable is a small grayscale icon.
119      * Grayscale here means "very close to a perfect gray"; icon means "no larger than 64dp".
120      *
121      * @param d The drawable to test.
122      * @return True if the bitmap is grayscale; false if it is color or too large to examine.
123      */
isGrayscaleIcon(Drawable d)124     public boolean isGrayscaleIcon(Drawable d) {
125         if (d == null) {
126             return false;
127         } else if (d instanceof BitmapDrawable) {
128             BitmapDrawable bd = (BitmapDrawable) d;
129             return bd.getBitmap() != null && isGrayscaleIcon(bd.getBitmap());
130         } else if (d instanceof AnimationDrawable) {
131             AnimationDrawable ad = (AnimationDrawable) d;
132             int count = ad.getNumberOfFrames();
133             return count > 0 && isGrayscaleIcon(ad.getFrame(0));
134         } else if (d instanceof VectorDrawable) {
135             // We just assume you're doing the right thing if using vectors
136             return true;
137         } else {
138             return false;
139         }
140     }
141 
isGrayscaleIcon(Context context, Icon icon)142     public boolean isGrayscaleIcon(Context context, Icon icon) {
143         if (icon == null) {
144             return false;
145         }
146         switch (icon.getType()) {
147             case Icon.TYPE_BITMAP:
148                 return isGrayscaleIcon(icon.getBitmap());
149             case Icon.TYPE_RESOURCE:
150                 return isGrayscaleIcon(context, icon.getResId());
151             default:
152                 return false;
153         }
154     }
155 
156     /**
157      * Checks whether a drawable with a resoure id is a small grayscale icon.
158      * Grayscale here means "very close to a perfect gray"; icon means "no larger than 64dp".
159      *
160      * @param context The context to load the drawable from.
161      * @return True if the bitmap is grayscale; false if it is color or too large to examine.
162      */
isGrayscaleIcon(Context context, int drawableResId)163     public boolean isGrayscaleIcon(Context context, int drawableResId) {
164         if (drawableResId != 0) {
165             try {
166                 return isGrayscaleIcon(context.getDrawable(drawableResId));
167             } catch (Resources.NotFoundException ex) {
168                 Log.e(TAG, "Drawable not found: " + drawableResId);
169                 return false;
170             }
171         } else {
172             return false;
173         }
174     }
175 
176     /**
177      * Inverts all the grayscale colors set by {@link android.text.style.TextAppearanceSpan}s on
178      * the text.
179      *
180      * @param charSequence The text to process.
181      * @return The color inverted text.
182      */
invertCharSequenceColors(CharSequence charSequence)183     public CharSequence invertCharSequenceColors(CharSequence charSequence) {
184         if (charSequence instanceof Spanned) {
185             Spanned ss = (Spanned) charSequence;
186             Object[] spans = ss.getSpans(0, ss.length(), Object.class);
187             SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString());
188             for (Object span : spans) {
189                 Object resultSpan = span;
190                 if (resultSpan instanceof CharacterStyle) {
191                     resultSpan = ((CharacterStyle) span).getUnderlying();
192                 }
193                 if (resultSpan instanceof TextAppearanceSpan) {
194                     TextAppearanceSpan processedSpan = processTextAppearanceSpan(
195                             (TextAppearanceSpan) span);
196                     if (processedSpan != resultSpan) {
197                         resultSpan = processedSpan;
198                     } else {
199                         // we need to still take the orgininal for wrapped spans
200                         resultSpan = span;
201                     }
202                 } else if (resultSpan instanceof ForegroundColorSpan) {
203                     ForegroundColorSpan originalSpan = (ForegroundColorSpan) resultSpan;
204                     int foregroundColor = originalSpan.getForegroundColor();
205                     resultSpan = new ForegroundColorSpan(processColor(foregroundColor));
206                 } else {
207                     resultSpan = span;
208                 }
209                 builder.setSpan(resultSpan, ss.getSpanStart(span), ss.getSpanEnd(span),
210                         ss.getSpanFlags(span));
211             }
212             return builder;
213         }
214         return charSequence;
215     }
216 
processTextAppearanceSpan(TextAppearanceSpan span)217     private TextAppearanceSpan processTextAppearanceSpan(TextAppearanceSpan span) {
218         ColorStateList colorStateList = span.getTextColor();
219         if (colorStateList != null) {
220             int[] colors = colorStateList.getColors();
221             boolean changed = false;
222             for (int i = 0; i < colors.length; i++) {
223                 if (ImageUtils.isGrayscale(colors[i])) {
224 
225                     // Allocate a new array so we don't change the colors in the old color state
226                     // list.
227                     if (!changed) {
228                         colors = Arrays.copyOf(colors, colors.length);
229                     }
230                     colors[i] = processColor(colors[i]);
231                     changed = true;
232                 }
233             }
234             if (changed) {
235                 return new TextAppearanceSpan(
236                         span.getFamily(), span.getTextStyle(), span.getTextSize(),
237                         new ColorStateList(colorStateList.getStates(), colors),
238                         span.getLinkTextColor());
239             }
240         }
241         return span;
242     }
243 
244     /**
245      * Clears all color spans of a text
246      * @param charSequence the input text
247      * @return the same text but without color spans
248      */
clearColorSpans(CharSequence charSequence)249     public static CharSequence clearColorSpans(CharSequence charSequence) {
250         if (charSequence instanceof Spanned) {
251             Spanned ss = (Spanned) charSequence;
252             Object[] spans = ss.getSpans(0, ss.length(), Object.class);
253             SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString());
254             for (Object span : spans) {
255                 Object resultSpan = span;
256                 if (resultSpan instanceof CharacterStyle) {
257                     resultSpan = ((CharacterStyle) span).getUnderlying();
258                 }
259                 if (resultSpan instanceof TextAppearanceSpan) {
260                     TextAppearanceSpan originalSpan = (TextAppearanceSpan) resultSpan;
261                     if (originalSpan.getTextColor() != null) {
262                         resultSpan = new TextAppearanceSpan(
263                                 originalSpan.getFamily(),
264                                 originalSpan.getTextStyle(),
265                                 originalSpan.getTextSize(),
266                                 null,
267                                 originalSpan.getLinkTextColor());
268                     }
269                 } else if (resultSpan instanceof ForegroundColorSpan
270                         || (resultSpan instanceof BackgroundColorSpan)) {
271                     continue;
272                 } else {
273                     resultSpan = span;
274                 }
275                 builder.setSpan(resultSpan, ss.getSpanStart(span), ss.getSpanEnd(span),
276                         ss.getSpanFlags(span));
277             }
278             return builder;
279         }
280         return charSequence;
281     }
282 
processColor(int color)283     private int processColor(int color) {
284         return Color.argb(Color.alpha(color),
285                 255 - Color.red(color),
286                 255 - Color.green(color),
287                 255 - Color.blue(color));
288     }
289 
290     /**
291      * Finds a suitable color such that there's enough contrast.
292      *
293      * @param color the color to start searching from.
294      * @param other the color to ensure contrast against. Assumed to be lighter than {@param color}
295      * @param findFg if true, we assume {@param color} is a foreground, otherwise a background.
296      * @param minRatio the minimum contrast ratio required.
297      * @return a color with the same hue as {@param color}, potentially darkened to meet the
298      *          contrast ratio.
299      */
findContrastColor(int color, int other, boolean findFg, double minRatio)300     public static int findContrastColor(int color, int other, boolean findFg, double minRatio) {
301         int fg = findFg ? color : other;
302         int bg = findFg ? other : color;
303         if (ColorUtilsFromCompat.calculateContrast(fg, bg) >= minRatio) {
304             return color;
305         }
306 
307         double[] lab = new double[3];
308         ColorUtilsFromCompat.colorToLAB(findFg ? fg : bg, lab);
309 
310         double low = 0, high = lab[0];
311         final double a = lab[1], b = lab[2];
312         for (int i = 0; i < 15 && high - low > 0.00001; i++) {
313             final double l = (low + high) / 2;
314             if (findFg) {
315                 fg = ColorUtilsFromCompat.LABToColor(l, a, b);
316             } else {
317                 bg = ColorUtilsFromCompat.LABToColor(l, a, b);
318             }
319             if (ColorUtilsFromCompat.calculateContrast(fg, bg) > minRatio) {
320                 low = l;
321             } else {
322                 high = l;
323             }
324         }
325         return ColorUtilsFromCompat.LABToColor(low, a, b);
326     }
327 
328     /**
329      * Finds a suitable alpha such that there's enough contrast.
330      *
331      * @param color the color to start searching from.
332      * @param backgroundColor the color to ensure contrast against.
333      * @param minRatio the minimum contrast ratio required.
334      * @return the same color as {@param color} with potentially modified alpha to meet contrast
335      */
findAlphaToMeetContrast(int color, int backgroundColor, double minRatio)336     public static int findAlphaToMeetContrast(int color, int backgroundColor, double minRatio) {
337         int fg = color;
338         int bg = backgroundColor;
339         if (ColorUtilsFromCompat.calculateContrast(fg, bg) >= minRatio) {
340             return color;
341         }
342         int startAlpha = Color.alpha(color);
343         int r = Color.red(color);
344         int g = Color.green(color);
345         int b = Color.blue(color);
346 
347         int low = startAlpha, high = 255;
348         for (int i = 0; i < 15 && high - low > 0; i++) {
349             final int alpha = (low + high) / 2;
350             fg = Color.argb(alpha, r, g, b);
351             if (ColorUtilsFromCompat.calculateContrast(fg, bg) > minRatio) {
352                 high = alpha;
353             } else {
354                 low = alpha;
355             }
356         }
357         return Color.argb(high, r, g, b);
358     }
359 
360     /**
361      * Finds a suitable color such that there's enough contrast.
362      *
363      * @param color the color to start searching from.
364      * @param other the color to ensure contrast against. Assumed to be darker than {@param color}
365      * @param findFg if true, we assume {@param color} is a foreground, otherwise a background.
366      * @param minRatio the minimum contrast ratio required.
367      * @return a color with the same hue as {@param color}, potentially darkened to meet the
368      *          contrast ratio.
369      */
findContrastColorAgainstDark(int color, int other, boolean findFg, double minRatio)370     public static int findContrastColorAgainstDark(int color, int other, boolean findFg,
371             double minRatio) {
372         int fg = findFg ? color : other;
373         int bg = findFg ? other : color;
374         if (ColorUtilsFromCompat.calculateContrast(fg, bg) >= minRatio) {
375             return color;
376         }
377 
378         float[] hsl = new float[3];
379         ColorUtilsFromCompat.colorToHSL(findFg ? fg : bg, hsl);
380 
381         float low = hsl[2], high = 1;
382         for (int i = 0; i < 15 && high - low > 0.00001; i++) {
383             final float l = (low + high) / 2;
384             hsl[2] = l;
385             if (findFg) {
386                 fg = ColorUtilsFromCompat.HSLToColor(hsl);
387             } else {
388                 bg = ColorUtilsFromCompat.HSLToColor(hsl);
389             }
390             if (ColorUtilsFromCompat.calculateContrast(fg, bg) > minRatio) {
391                 high = l;
392             } else {
393                 low = l;
394             }
395         }
396         return findFg ? fg : bg;
397     }
398 
ensureTextContrastOnBlack(int color)399     public static int ensureTextContrastOnBlack(int color) {
400         return findContrastColorAgainstDark(color, Color.BLACK, true /* fg */, 12);
401     }
402 
403      /**
404      * Finds a large text color with sufficient contrast over bg that has the same or darker hue as
405      * the original color, depending on the value of {@code isBgDarker}.
406      *
407      * @param isBgDarker {@code true} if {@code bg} is darker than {@code color}.
408      */
ensureLargeTextContrast(int color, int bg, boolean isBgDarker)409     public static int ensureLargeTextContrast(int color, int bg, boolean isBgDarker) {
410         return isBgDarker
411                 ? findContrastColorAgainstDark(color, bg, true, 3)
412                 : findContrastColor(color, bg, true, 3);
413     }
414 
415     /**
416      * Finds a text color with sufficient contrast over bg that has the same or darker hue as the
417      * original color, depending on the value of {@code isBgDarker}.
418      *
419      * @param isBgDarker {@code true} if {@code bg} is darker than {@code color}.
420      */
ensureTextContrast(int color, int bg, boolean isBgDarker)421     private static int ensureTextContrast(int color, int bg, boolean isBgDarker) {
422         return isBgDarker
423                 ? findContrastColorAgainstDark(color, bg, true, 4.5)
424                 : findContrastColor(color, bg, true, 4.5);
425     }
426 
427     /** Finds a background color for a text view with given text color and hint text color, that
428      * has the same hue as the original color.
429      */
ensureTextBackgroundColor(int color, int textColor, int hintColor)430     public static int ensureTextBackgroundColor(int color, int textColor, int hintColor) {
431         color = findContrastColor(color, hintColor, false, 3.0);
432         return findContrastColor(color, textColor, false, 4.5);
433     }
434 
contrastChange(int colorOld, int colorNew, int bg)435     private static String contrastChange(int colorOld, int colorNew, int bg) {
436         return String.format("from %.2f:1 to %.2f:1",
437                 ColorUtilsFromCompat.calculateContrast(colorOld, bg),
438                 ColorUtilsFromCompat.calculateContrast(colorNew, bg));
439     }
440 
441     /**
442      * Resolves {@param color} to an actual color if it is {@link Notification#COLOR_DEFAULT}
443      */
resolveColor(Context context, int color)444     public static int resolveColor(Context context, int color) {
445         if (color == Notification.COLOR_DEFAULT) {
446             return context.getColor(com.android.internal.R.color.notification_icon_default_color);
447         }
448         return color;
449     }
450 
451     /**
452      * Resolves a Notification's color such that it has enough contrast to be used as the
453      * color for the Notification's action and header text on a background that is lighter than
454      * {@code notificationColor}.
455      *
456      * @see {@link #resolveContrastColor(Context, int, boolean)}
457      */
resolveContrastColor(Context context, int notificationColor, int backgroundColor)458     public static int resolveContrastColor(Context context, int notificationColor,
459             int backgroundColor) {
460         return NotificationColorUtil.resolveContrastColor(context, notificationColor,
461                 backgroundColor, false /* isDark */);
462     }
463 
464     /**
465      * Resolves a Notification's color such that it has enough contrast to be used as the
466      * color for the Notification's action and header text.
467      *
468      * @param notificationColor the color of the notification or {@link Notification#COLOR_DEFAULT}
469      * @param backgroundColor the background color to ensure the contrast against.
470      * @param isDark whether or not the {@code notificationColor} will be placed on a background
471      *               that is darker than the color itself
472      * @return a color of the same hue with enough contrast against the backgrounds.
473      */
resolveContrastColor(Context context, int notificationColor, int backgroundColor, boolean isDark)474     public static int resolveContrastColor(Context context, int notificationColor,
475             int backgroundColor, boolean isDark) {
476         final int resolvedColor = resolveColor(context, notificationColor);
477 
478         final int actionBg = context.getColor(
479                 com.android.internal.R.color.notification_action_list);
480 
481         int color = resolvedColor;
482         color = NotificationColorUtil.ensureLargeTextContrast(color, actionBg, isDark);
483         color = NotificationColorUtil.ensureTextContrast(color, backgroundColor, isDark);
484 
485         if (color != resolvedColor) {
486             if (DEBUG){
487                 Log.w(TAG, String.format(
488                         "Enhanced contrast of notification for %s %s (over action)"
489                                 + " and %s (over background) by changing #%s to %s",
490                         context.getPackageName(),
491                         NotificationColorUtil.contrastChange(resolvedColor, color, actionBg),
492                         NotificationColorUtil.contrastChange(resolvedColor, color, backgroundColor),
493                         Integer.toHexString(resolvedColor), Integer.toHexString(color)));
494             }
495         }
496         return color;
497     }
498 
499     /**
500      * Change a color by a specified value
501      * @param baseColor the base color to lighten
502      * @param amount the amount to lighten the color from 0 to 100. This corresponds to the L
503      *               increase in the LAB color space. A negative value will darken the color and
504      *               a positive will lighten it.
505      * @return the changed color
506      */
changeColorLightness(int baseColor, int amount)507     public static int changeColorLightness(int baseColor, int amount) {
508         final double[] result = ColorUtilsFromCompat.getTempDouble3Array();
509         ColorUtilsFromCompat.colorToLAB(baseColor, result);
510         result[0] = Math.max(Math.min(100, result[0] + amount), 0);
511         return ColorUtilsFromCompat.LABToColor(result[0], result[1], result[2]);
512     }
513 
resolveAmbientColor(Context context, int notificationColor)514     public static int resolveAmbientColor(Context context, int notificationColor) {
515         final int resolvedColor = resolveColor(context, notificationColor);
516 
517         int color = resolvedColor;
518         color = NotificationColorUtil.ensureTextContrastOnBlack(color);
519 
520         if (color != resolvedColor) {
521             if (DEBUG){
522                 Log.w(TAG, String.format(
523                         "Ambient contrast of notification for %s is %s (over black)"
524                                 + " by changing #%s to #%s",
525                         context.getPackageName(),
526                         NotificationColorUtil.contrastChange(resolvedColor, color, Color.BLACK),
527                         Integer.toHexString(resolvedColor), Integer.toHexString(color)));
528             }
529         }
530         return color;
531     }
532 
resolvePrimaryColor(Context context, int backgroundColor)533     public static int resolvePrimaryColor(Context context, int backgroundColor) {
534         boolean useDark = shouldUseDark(backgroundColor);
535         if (useDark) {
536             return context.getColor(
537                     com.android.internal.R.color.notification_primary_text_color_light);
538         } else {
539             return context.getColor(
540                     com.android.internal.R.color.notification_primary_text_color_dark);
541         }
542     }
543 
resolveSecondaryColor(Context context, int backgroundColor)544     public static int resolveSecondaryColor(Context context, int backgroundColor) {
545         boolean useDark = shouldUseDark(backgroundColor);
546         if (useDark) {
547             return context.getColor(
548                     com.android.internal.R.color.notification_secondary_text_color_light);
549         } else {
550             return context.getColor(
551                     com.android.internal.R.color.notification_secondary_text_color_dark);
552         }
553     }
554 
resolveActionBarColor(Context context, int backgroundColor)555     public static int resolveActionBarColor(Context context, int backgroundColor) {
556         if (backgroundColor == Notification.COLOR_DEFAULT) {
557             return context.getColor(com.android.internal.R.color.notification_action_list);
558         }
559         return getShiftedColor(backgroundColor, 7);
560     }
561 
562     /**
563      * Get a color that stays in the same tint, but darkens or lightens it by a certain
564      * amount.
565      * This also looks at the lightness of the provided color and shifts it appropriately.
566      *
567      * @param color the base color to use
568      * @param amount the amount from 1 to 100 how much to modify the color
569      * @return the now color that was modified
570      */
getShiftedColor(int color, int amount)571     public static int getShiftedColor(int color, int amount) {
572         final double[] result = ColorUtilsFromCompat.getTempDouble3Array();
573         ColorUtilsFromCompat.colorToLAB(color, result);
574         if (result[0] >= 4) {
575             result[0] = Math.max(0, result[0] - amount);
576         } else {
577             result[0] = Math.min(100, result[0] + amount);
578         }
579         return ColorUtilsFromCompat.LABToColor(result[0], result[1], result[2]);
580     }
581 
shouldUseDark(int backgroundColor)582     private static boolean shouldUseDark(int backgroundColor) {
583         boolean useDark = backgroundColor == Notification.COLOR_DEFAULT;
584         if (!useDark) {
585             useDark = ColorUtilsFromCompat.calculateLuminance(backgroundColor) > 0.5;
586         }
587         return useDark;
588     }
589 
calculateLuminance(int backgroundColor)590     public static double calculateLuminance(int backgroundColor) {
591         return ColorUtilsFromCompat.calculateLuminance(backgroundColor);
592     }
593 
594 
calculateContrast(int foregroundColor, int backgroundColor)595     public static double calculateContrast(int foregroundColor, int backgroundColor) {
596         return ColorUtilsFromCompat.calculateContrast(foregroundColor, backgroundColor);
597     }
598 
satisfiesTextContrast(int backgroundColor, int foregroundColor)599     public static boolean satisfiesTextContrast(int backgroundColor, int foregroundColor) {
600         return NotificationColorUtil.calculateContrast(foregroundColor, backgroundColor) >= 4.5;
601     }
602 
603     /**
604      * Composite two potentially translucent colors over each other and returns the result.
605      */
compositeColors(int foreground, int background)606     public static int compositeColors(int foreground, int background) {
607         return ColorUtilsFromCompat.compositeColors(foreground, background);
608     }
609 
isColorLight(int backgroundColor)610     public static boolean isColorLight(int backgroundColor) {
611         return calculateLuminance(backgroundColor) > 0.5f;
612     }
613 
614     /**
615      * Framework copy of functions needed from android.support.v4.graphics.ColorUtils.
616      */
617     private static class ColorUtilsFromCompat {
618         private static final double XYZ_WHITE_REFERENCE_X = 95.047;
619         private static final double XYZ_WHITE_REFERENCE_Y = 100;
620         private static final double XYZ_WHITE_REFERENCE_Z = 108.883;
621         private static final double XYZ_EPSILON = 0.008856;
622         private static final double XYZ_KAPPA = 903.3;
623 
624         private static final int MIN_ALPHA_SEARCH_MAX_ITERATIONS = 10;
625         private static final int MIN_ALPHA_SEARCH_PRECISION = 1;
626 
627         private static final ThreadLocal<double[]> TEMP_ARRAY = new ThreadLocal<>();
628 
ColorUtilsFromCompat()629         private ColorUtilsFromCompat() {}
630 
631         /**
632          * Composite two potentially translucent colors over each other and returns the result.
633          */
compositeColors(@olorInt int foreground, @ColorInt int background)634         public static int compositeColors(@ColorInt int foreground, @ColorInt int background) {
635             int bgAlpha = Color.alpha(background);
636             int fgAlpha = Color.alpha(foreground);
637             int a = compositeAlpha(fgAlpha, bgAlpha);
638 
639             int r = compositeComponent(Color.red(foreground), fgAlpha,
640                     Color.red(background), bgAlpha, a);
641             int g = compositeComponent(Color.green(foreground), fgAlpha,
642                     Color.green(background), bgAlpha, a);
643             int b = compositeComponent(Color.blue(foreground), fgAlpha,
644                     Color.blue(background), bgAlpha, a);
645 
646             return Color.argb(a, r, g, b);
647         }
648 
compositeAlpha(int foregroundAlpha, int backgroundAlpha)649         private static int compositeAlpha(int foregroundAlpha, int backgroundAlpha) {
650             return 0xFF - (((0xFF - backgroundAlpha) * (0xFF - foregroundAlpha)) / 0xFF);
651         }
652 
compositeComponent(int fgC, int fgA, int bgC, int bgA, int a)653         private static int compositeComponent(int fgC, int fgA, int bgC, int bgA, int a) {
654             if (a == 0) return 0;
655             return ((0xFF * fgC * fgA) + (bgC * bgA * (0xFF - fgA))) / (a * 0xFF);
656         }
657 
658         /**
659          * Returns the luminance of a color as a float between {@code 0.0} and {@code 1.0}.
660          * <p>Defined as the Y component in the XYZ representation of {@code color}.</p>
661          */
662         @FloatRange(from = 0.0, to = 1.0)
calculateLuminance(@olorInt int color)663         public static double calculateLuminance(@ColorInt int color) {
664             final double[] result = getTempDouble3Array();
665             colorToXYZ(color, result);
666             // Luminance is the Y component
667             return result[1] / 100;
668         }
669 
670         /**
671          * Returns the contrast ratio between {@code foreground} and {@code background}.
672          * {@code background} must be opaque.
673          * <p>
674          * Formula defined
675          * <a href="http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef">here</a>.
676          */
calculateContrast(@olorInt int foreground, @ColorInt int background)677         public static double calculateContrast(@ColorInt int foreground, @ColorInt int background) {
678             if (Color.alpha(background) != 255) {
679                 Log.wtf(TAG, "background can not be translucent: #"
680                         + Integer.toHexString(background));
681             }
682             if (Color.alpha(foreground) < 255) {
683                 // If the foreground is translucent, composite the foreground over the background
684                 foreground = compositeColors(foreground, background);
685             }
686 
687             final double luminance1 = calculateLuminance(foreground) + 0.05;
688             final double luminance2 = calculateLuminance(background) + 0.05;
689 
690             // Now return the lighter luminance divided by the darker luminance
691             return Math.max(luminance1, luminance2) / Math.min(luminance1, luminance2);
692         }
693 
694         /**
695          * Convert the ARGB color to its CIE Lab representative components.
696          *
697          * @param color  the ARGB color to convert. The alpha component is ignored
698          * @param outLab 3-element array which holds the resulting LAB components
699          */
colorToLAB(@olorInt int color, @NonNull double[] outLab)700         public static void colorToLAB(@ColorInt int color, @NonNull double[] outLab) {
701             RGBToLAB(Color.red(color), Color.green(color), Color.blue(color), outLab);
702         }
703 
704         /**
705          * Convert RGB components to its CIE Lab representative components.
706          *
707          * <ul>
708          * <li>outLab[0] is L [0 ...100)</li>
709          * <li>outLab[1] is a [-128...127)</li>
710          * <li>outLab[2] is b [-128...127)</li>
711          * </ul>
712          *
713          * @param r      red component value [0..255]
714          * @param g      green component value [0..255]
715          * @param b      blue component value [0..255]
716          * @param outLab 3-element array which holds the resulting LAB components
717          */
RGBToLAB(@ntRangefrom = 0x0, to = 0xFF) int r, @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b, @NonNull double[] outLab)718         public static void RGBToLAB(@IntRange(from = 0x0, to = 0xFF) int r,
719                 @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b,
720                 @NonNull double[] outLab) {
721             // First we convert RGB to XYZ
722             RGBToXYZ(r, g, b, outLab);
723             // outLab now contains XYZ
724             XYZToLAB(outLab[0], outLab[1], outLab[2], outLab);
725             // outLab now contains LAB representation
726         }
727 
728         /**
729          * Convert the ARGB color to it's CIE XYZ representative components.
730          *
731          * <p>The resulting XYZ representation will use the D65 illuminant and the CIE
732          * 2° Standard Observer (1931).</p>
733          *
734          * <ul>
735          * <li>outXyz[0] is X [0 ...95.047)</li>
736          * <li>outXyz[1] is Y [0...100)</li>
737          * <li>outXyz[2] is Z [0...108.883)</li>
738          * </ul>
739          *
740          * @param color  the ARGB color to convert. The alpha component is ignored
741          * @param outXyz 3-element array which holds the resulting LAB components
742          */
colorToXYZ(@olorInt int color, @NonNull double[] outXyz)743         public static void colorToXYZ(@ColorInt int color, @NonNull double[] outXyz) {
744             RGBToXYZ(Color.red(color), Color.green(color), Color.blue(color), outXyz);
745         }
746 
747         /**
748          * Convert RGB components to it's CIE XYZ representative components.
749          *
750          * <p>The resulting XYZ representation will use the D65 illuminant and the CIE
751          * 2° Standard Observer (1931).</p>
752          *
753          * <ul>
754          * <li>outXyz[0] is X [0 ...95.047)</li>
755          * <li>outXyz[1] is Y [0...100)</li>
756          * <li>outXyz[2] is Z [0...108.883)</li>
757          * </ul>
758          *
759          * @param r      red component value [0..255]
760          * @param g      green component value [0..255]
761          * @param b      blue component value [0..255]
762          * @param outXyz 3-element array which holds the resulting XYZ components
763          */
RGBToXYZ(@ntRangefrom = 0x0, to = 0xFF) int r, @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b, @NonNull double[] outXyz)764         public static void RGBToXYZ(@IntRange(from = 0x0, to = 0xFF) int r,
765                 @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b,
766                 @NonNull double[] outXyz) {
767             if (outXyz.length != 3) {
768                 throw new IllegalArgumentException("outXyz must have a length of 3.");
769             }
770 
771             double sr = r / 255.0;
772             sr = sr < 0.04045 ? sr / 12.92 : Math.pow((sr + 0.055) / 1.055, 2.4);
773             double sg = g / 255.0;
774             sg = sg < 0.04045 ? sg / 12.92 : Math.pow((sg + 0.055) / 1.055, 2.4);
775             double sb = b / 255.0;
776             sb = sb < 0.04045 ? sb / 12.92 : Math.pow((sb + 0.055) / 1.055, 2.4);
777 
778             outXyz[0] = 100 * (sr * 0.4124 + sg * 0.3576 + sb * 0.1805);
779             outXyz[1] = 100 * (sr * 0.2126 + sg * 0.7152 + sb * 0.0722);
780             outXyz[2] = 100 * (sr * 0.0193 + sg * 0.1192 + sb * 0.9505);
781         }
782 
783         /**
784          * Converts a color from CIE XYZ to CIE Lab representation.
785          *
786          * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE
787          * 2° Standard Observer (1931).</p>
788          *
789          * <ul>
790          * <li>outLab[0] is L [0 ...100)</li>
791          * <li>outLab[1] is a [-128...127)</li>
792          * <li>outLab[2] is b [-128...127)</li>
793          * </ul>
794          *
795          * @param x      X component value [0...95.047)
796          * @param y      Y component value [0...100)
797          * @param z      Z component value [0...108.883)
798          * @param outLab 3-element array which holds the resulting Lab components
799          */
800         public static void XYZToLAB(@FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_X) double x,
801                 @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Y) double y,
802                 @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Z) double z,
803                 @NonNull double[] outLab) {
804             if (outLab.length != 3) {
805                 throw new IllegalArgumentException("outLab must have a length of 3.");
806             }
807             x = pivotXyzComponent(x / XYZ_WHITE_REFERENCE_X);
808             y = pivotXyzComponent(y / XYZ_WHITE_REFERENCE_Y);
809             z = pivotXyzComponent(z / XYZ_WHITE_REFERENCE_Z);
810             outLab[0] = Math.max(0, 116 * y - 16);
811             outLab[1] = 500 * (x - y);
812             outLab[2] = 200 * (y - z);
813         }
814 
815         /**
816          * Converts a color from CIE Lab to CIE XYZ representation.
817          *
818          * <p>The resulting XYZ representation will use the D65 illuminant and the CIE
819          * 2° Standard Observer (1931).</p>
820          *
821          * <ul>
822          * <li>outXyz[0] is X [0 ...95.047)</li>
823          * <li>outXyz[1] is Y [0...100)</li>
824          * <li>outXyz[2] is Z [0...108.883)</li>
825          * </ul>
826          *
827          * @param l      L component value [0...100)
828          * @param a      A component value [-128...127)
829          * @param b      B component value [-128...127)
830          * @param outXyz 3-element array which holds the resulting XYZ components
831          */
832         public static void LABToXYZ(@FloatRange(from = 0f, to = 100) final double l,
833                 @FloatRange(from = -128, to = 127) final double a,
834                 @FloatRange(from = -128, to = 127) final double b,
835                 @NonNull double[] outXyz) {
836             final double fy = (l + 16) / 116;
837             final double fx = a / 500 + fy;
838             final double fz = fy - b / 200;
839 
840             double tmp = Math.pow(fx, 3);
841             final double xr = tmp > XYZ_EPSILON ? tmp : (116 * fx - 16) / XYZ_KAPPA;
842             final double yr = l > XYZ_KAPPA * XYZ_EPSILON ? Math.pow(fy, 3) : l / XYZ_KAPPA;
843 
844             tmp = Math.pow(fz, 3);
845             final double zr = tmp > XYZ_EPSILON ? tmp : (116 * fz - 16) / XYZ_KAPPA;
846 
847             outXyz[0] = xr * XYZ_WHITE_REFERENCE_X;
848             outXyz[1] = yr * XYZ_WHITE_REFERENCE_Y;
849             outXyz[2] = zr * XYZ_WHITE_REFERENCE_Z;
850         }
851 
852         /**
853          * Converts a color from CIE XYZ to its RGB representation.
854          *
855          * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE
856          * 2° Standard Observer (1931).</p>
857          *
858          * @param x X component value [0...95.047)
859          * @param y Y component value [0...100)
860          * @param z Z component value [0...108.883)
861          * @return int containing the RGB representation
862          */
863         @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)864         public static int XYZToColor(@FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_X) double x,
865                 @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Y) double y,
866                 @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Z) double z) {
867             double r = (x * 3.2406 + y * -1.5372 + z * -0.4986) / 100;
868             double g = (x * -0.9689 + y * 1.8758 + z * 0.0415) / 100;
869             double b = (x * 0.0557 + y * -0.2040 + z * 1.0570) / 100;
870 
871             r = r > 0.0031308 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : 12.92 * r;
872             g = g > 0.0031308 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : 12.92 * g;
873             b = b > 0.0031308 ? 1.055 * Math.pow(b, 1 / 2.4) - 0.055 : 12.92 * b;
874 
875             return Color.rgb(
876                     constrain((int) Math.round(r * 255), 0, 255),
877                     constrain((int) Math.round(g * 255), 0, 255),
878                     constrain((int) Math.round(b * 255), 0, 255));
879         }
880 
881         /**
882          * Converts a color from CIE Lab to its RGB representation.
883          *
884          * @param l L component value [0...100]
885          * @param a A component value [-128...127]
886          * @param b B component value [-128...127]
887          * @return int containing the RGB representation
888          */
889         @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)890         public static int LABToColor(@FloatRange(from = 0f, to = 100) final double l,
891                 @FloatRange(from = -128, to = 127) final double a,
892                 @FloatRange(from = -128, to = 127) final double b) {
893             final double[] result = getTempDouble3Array();
894             LABToXYZ(l, a, b, result);
895             return XYZToColor(result[0], result[1], result[2]);
896         }
897 
constrain(int amount, int low, int high)898         private static int constrain(int amount, int low, int high) {
899             return amount < low ? low : (amount > high ? high : amount);
900         }
901 
constrain(float amount, float low, float high)902         private static float constrain(float amount, float low, float high) {
903             return amount < low ? low : (amount > high ? high : amount);
904         }
905 
pivotXyzComponent(double component)906         private static double pivotXyzComponent(double component) {
907             return component > XYZ_EPSILON
908                     ? Math.pow(component, 1 / 3.0)
909                     : (XYZ_KAPPA * component + 16) / 116;
910         }
911 
getTempDouble3Array()912         public static double[] getTempDouble3Array() {
913             double[] result = TEMP_ARRAY.get();
914             if (result == null) {
915                 result = new double[3];
916                 TEMP_ARRAY.set(result);
917             }
918             return result;
919         }
920 
921         /**
922          * Convert HSL (hue-saturation-lightness) components to a RGB color.
923          * <ul>
924          * <li>hsl[0] is Hue [0 .. 360)</li>
925          * <li>hsl[1] is Saturation [0...1]</li>
926          * <li>hsl[2] is Lightness [0...1]</li>
927          * </ul>
928          * If hsv values are out of range, they are pinned.
929          *
930          * @param hsl 3-element array which holds the input HSL components
931          * @return the resulting RGB color
932          */
933         @ColorInt
HSLToColor(@onNull float[] hsl)934         public static int HSLToColor(@NonNull float[] hsl) {
935             final float h = hsl[0];
936             final float s = hsl[1];
937             final float l = hsl[2];
938 
939             final float c = (1f - Math.abs(2 * l - 1f)) * s;
940             final float m = l - 0.5f * c;
941             final float x = c * (1f - Math.abs((h / 60f % 2f) - 1f));
942 
943             final int hueSegment = (int) h / 60;
944 
945             int r = 0, g = 0, b = 0;
946 
947             switch (hueSegment) {
948                 case 0:
949                     r = Math.round(255 * (c + m));
950                     g = Math.round(255 * (x + m));
951                     b = Math.round(255 * m);
952                     break;
953                 case 1:
954                     r = Math.round(255 * (x + m));
955                     g = Math.round(255 * (c + m));
956                     b = Math.round(255 * m);
957                     break;
958                 case 2:
959                     r = Math.round(255 * m);
960                     g = Math.round(255 * (c + m));
961                     b = Math.round(255 * (x + m));
962                     break;
963                 case 3:
964                     r = Math.round(255 * m);
965                     g = Math.round(255 * (x + m));
966                     b = Math.round(255 * (c + m));
967                     break;
968                 case 4:
969                     r = Math.round(255 * (x + m));
970                     g = Math.round(255 * m);
971                     b = Math.round(255 * (c + m));
972                     break;
973                 case 5:
974                 case 6:
975                     r = Math.round(255 * (c + m));
976                     g = Math.round(255 * m);
977                     b = Math.round(255 * (x + m));
978                     break;
979             }
980 
981             r = constrain(r, 0, 255);
982             g = constrain(g, 0, 255);
983             b = constrain(b, 0, 255);
984 
985             return Color.rgb(r, g, b);
986         }
987 
988         /**
989          * Convert the ARGB color to its HSL (hue-saturation-lightness) components.
990          * <ul>
991          * <li>outHsl[0] is Hue [0 .. 360)</li>
992          * <li>outHsl[1] is Saturation [0...1]</li>
993          * <li>outHsl[2] is Lightness [0...1]</li>
994          * </ul>
995          *
996          * @param color  the ARGB color to convert. The alpha component is ignored
997          * @param outHsl 3-element array which holds the resulting HSL components
998          */
colorToHSL(@olorInt int color, @NonNull float[] outHsl)999         public static void colorToHSL(@ColorInt int color, @NonNull float[] outHsl) {
1000             RGBToHSL(Color.red(color), Color.green(color), Color.blue(color), outHsl);
1001         }
1002 
1003         /**
1004          * Convert RGB components to HSL (hue-saturation-lightness).
1005          * <ul>
1006          * <li>outHsl[0] is Hue [0 .. 360)</li>
1007          * <li>outHsl[1] is Saturation [0...1]</li>
1008          * <li>outHsl[2] is Lightness [0...1]</li>
1009          * </ul>
1010          *
1011          * @param r      red component value [0..255]
1012          * @param g      green component value [0..255]
1013          * @param b      blue component value [0..255]
1014          * @param outHsl 3-element array which holds the resulting HSL components
1015          */
RGBToHSL(@ntRangefrom = 0x0, to = 0xFF) int r, @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b, @NonNull float[] outHsl)1016         public static void RGBToHSL(@IntRange(from = 0x0, to = 0xFF) int r,
1017                 @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b,
1018                 @NonNull float[] outHsl) {
1019             final float rf = r / 255f;
1020             final float gf = g / 255f;
1021             final float bf = b / 255f;
1022 
1023             final float max = Math.max(rf, Math.max(gf, bf));
1024             final float min = Math.min(rf, Math.min(gf, bf));
1025             final float deltaMaxMin = max - min;
1026 
1027             float h, s;
1028             float l = (max + min) / 2f;
1029 
1030             if (max == min) {
1031                 // Monochromatic
1032                 h = s = 0f;
1033             } else {
1034                 if (max == rf) {
1035                     h = ((gf - bf) / deltaMaxMin) % 6f;
1036                 } else if (max == gf) {
1037                     h = ((bf - rf) / deltaMaxMin) + 2f;
1038                 } else {
1039                     h = ((rf - gf) / deltaMaxMin) + 4f;
1040                 }
1041 
1042                 s = deltaMaxMin / (1f - Math.abs(2f * l - 1f));
1043             }
1044 
1045             h = (h * 60f) % 360f;
1046             if (h < 0) {
1047                 h += 360f;
1048             }
1049 
1050             outHsl[0] = constrain(h, 0f, 360f);
1051             outHsl[1] = constrain(s, 0f, 1f);
1052             outHsl[2] = constrain(l, 0f, 1f);
1053         }
1054 
1055     }
1056 }
1057