NotificationColorUtil.java revision f9d13f6d7a6fda22620cd4eab74ec98cafdbd147
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 17package com.android.internal.util; 18 19import android.annotation.ColorInt; 20import android.annotation.FloatRange; 21import android.annotation.IntRange; 22import android.annotation.NonNull; 23import android.app.Notification; 24import android.content.Context; 25import android.content.res.ColorStateList; 26import android.content.res.Resources; 27import android.graphics.Bitmap; 28import android.graphics.Color; 29import android.graphics.drawable.AnimationDrawable; 30import android.graphics.drawable.BitmapDrawable; 31import android.graphics.drawable.Drawable; 32import android.graphics.drawable.Icon; 33import android.graphics.drawable.VectorDrawable; 34import android.text.SpannableStringBuilder; 35import android.text.Spanned; 36import android.text.style.TextAppearanceSpan; 37import android.util.Log; 38import android.util.Pair; 39 40import java.util.Arrays; 41import java.util.WeakHashMap; 42 43/** 44 * Helper class to process legacy (Holo) notifications to make them look like material notifications. 45 * 46 * @hide 47 */ 48public class NotificationColorUtil { 49 50 private static final String TAG = "NotificationColorUtil"; 51 private static final boolean DEBUG = false; 52 53 private static final Object sLock = new Object(); 54 private static NotificationColorUtil sInstance; 55 56 private final ImageUtils mImageUtils = new ImageUtils(); 57 private final WeakHashMap<Bitmap, Pair<Boolean, Integer>> mGrayscaleBitmapCache = 58 new WeakHashMap<Bitmap, Pair<Boolean, Integer>>(); 59 60 private final int mGrayscaleIconMaxSize; // @dimen/notification_large_icon_width (64dp) 61 62 public static NotificationColorUtil getInstance(Context context) { 63 synchronized (sLock) { 64 if (sInstance == null) { 65 sInstance = new NotificationColorUtil(context); 66 } 67 return sInstance; 68 } 69 } 70 71 private NotificationColorUtil(Context context) { 72 mGrayscaleIconMaxSize = context.getResources().getDimensionPixelSize( 73 com.android.internal.R.dimen.notification_large_icon_width); 74 } 75 76 /** 77 * Checks whether a Bitmap is a small grayscale icon. 78 * Grayscale here means "very close to a perfect gray"; icon means "no larger than 64dp". 79 * 80 * @param bitmap The bitmap to test. 81 * @return True if the bitmap is grayscale; false if it is color or too large to examine. 82 */ 83 public boolean isGrayscaleIcon(Bitmap bitmap) { 84 // quick test: reject large bitmaps 85 if (bitmap.getWidth() > mGrayscaleIconMaxSize 86 || bitmap.getHeight() > mGrayscaleIconMaxSize) { 87 return false; 88 } 89 90 synchronized (sLock) { 91 Pair<Boolean, Integer> cached = mGrayscaleBitmapCache.get(bitmap); 92 if (cached != null) { 93 if (cached.second == bitmap.getGenerationId()) { 94 return cached.first; 95 } 96 } 97 } 98 boolean result; 99 int generationId; 100 synchronized (mImageUtils) { 101 result = mImageUtils.isGrayscale(bitmap); 102 103 // generationId and the check whether the Bitmap is grayscale can't be read atomically 104 // here. However, since the thread is in the process of posting the notification, we can 105 // assume that it doesn't modify the bitmap while we are checking the pixels. 106 generationId = bitmap.getGenerationId(); 107 } 108 synchronized (sLock) { 109 mGrayscaleBitmapCache.put(bitmap, Pair.create(result, generationId)); 110 } 111 return result; 112 } 113 114 /** 115 * Checks whether a Drawable is a small grayscale icon. 116 * Grayscale here means "very close to a perfect gray"; icon means "no larger than 64dp". 117 * 118 * @param d The drawable to test. 119 * @return True if the bitmap is grayscale; false if it is color or too large to examine. 120 */ 121 public boolean isGrayscaleIcon(Drawable d) { 122 if (d == null) { 123 return false; 124 } else if (d instanceof BitmapDrawable) { 125 BitmapDrawable bd = (BitmapDrawable) d; 126 return bd.getBitmap() != null && isGrayscaleIcon(bd.getBitmap()); 127 } else if (d instanceof AnimationDrawable) { 128 AnimationDrawable ad = (AnimationDrawable) d; 129 int count = ad.getNumberOfFrames(); 130 return count > 0 && isGrayscaleIcon(ad.getFrame(0)); 131 } else if (d instanceof VectorDrawable) { 132 // We just assume you're doing the right thing if using vectors 133 return true; 134 } else { 135 return false; 136 } 137 } 138 139 public boolean isGrayscaleIcon(Context context, Icon icon) { 140 if (icon == null) { 141 return false; 142 } 143 switch (icon.getType()) { 144 case Icon.TYPE_BITMAP: 145 return isGrayscaleIcon(icon.getBitmap()); 146 case Icon.TYPE_RESOURCE: 147 return isGrayscaleIcon(context, icon.getResId()); 148 default: 149 return false; 150 } 151 } 152 153 /** 154 * Checks whether a drawable with a resoure id is a small grayscale icon. 155 * Grayscale here means "very close to a perfect gray"; icon means "no larger than 64dp". 156 * 157 * @param context The context to load the drawable from. 158 * @return True if the bitmap is grayscale; false if it is color or too large to examine. 159 */ 160 public boolean isGrayscaleIcon(Context context, int drawableResId) { 161 if (drawableResId != 0) { 162 try { 163 return isGrayscaleIcon(context.getDrawable(drawableResId)); 164 } catch (Resources.NotFoundException ex) { 165 Log.e(TAG, "Drawable not found: " + drawableResId); 166 return false; 167 } 168 } else { 169 return false; 170 } 171 } 172 173 /** 174 * Inverts all the grayscale colors set by {@link android.text.style.TextAppearanceSpan}s on 175 * the text. 176 * 177 * @param charSequence The text to process. 178 * @return The color inverted text. 179 */ 180 public CharSequence invertCharSequenceColors(CharSequence charSequence) { 181 if (charSequence instanceof Spanned) { 182 Spanned ss = (Spanned) charSequence; 183 Object[] spans = ss.getSpans(0, ss.length(), Object.class); 184 SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString()); 185 for (Object span : spans) { 186 Object resultSpan = span; 187 if (span instanceof TextAppearanceSpan) { 188 resultSpan = processTextAppearanceSpan((TextAppearanceSpan) span); 189 } 190 builder.setSpan(resultSpan, ss.getSpanStart(span), ss.getSpanEnd(span), 191 ss.getSpanFlags(span)); 192 } 193 return builder; 194 } 195 return charSequence; 196 } 197 198 private TextAppearanceSpan processTextAppearanceSpan(TextAppearanceSpan span) { 199 ColorStateList colorStateList = span.getTextColor(); 200 if (colorStateList != null) { 201 int[] colors = colorStateList.getColors(); 202 boolean changed = false; 203 for (int i = 0; i < colors.length; i++) { 204 if (ImageUtils.isGrayscale(colors[i])) { 205 206 // Allocate a new array so we don't change the colors in the old color state 207 // list. 208 if (!changed) { 209 colors = Arrays.copyOf(colors, colors.length); 210 } 211 colors[i] = processColor(colors[i]); 212 changed = true; 213 } 214 } 215 if (changed) { 216 return new TextAppearanceSpan( 217 span.getFamily(), span.getTextStyle(), span.getTextSize(), 218 new ColorStateList(colorStateList.getStates(), colors), 219 span.getLinkTextColor()); 220 } 221 } 222 return span; 223 } 224 225 private int processColor(int color) { 226 return Color.argb(Color.alpha(color), 227 255 - Color.red(color), 228 255 - Color.green(color), 229 255 - Color.blue(color)); 230 } 231 232 /** 233 * Finds a suitable color such that there's enough contrast. 234 * 235 * @param color the color to start searching from. 236 * @param other the color to ensure contrast against. Assumed to be lighter than {@param color} 237 * @param findFg if true, we assume {@param color} is a foreground, otherwise a background. 238 * @param minRatio the minimum contrast ratio required. 239 * @return a color with the same hue as {@param color}, potentially darkened to meet the 240 * contrast ratio. 241 */ 242 private static int findContrastColor(int color, int other, boolean findFg, double minRatio) { 243 int fg = findFg ? color : other; 244 int bg = findFg ? other : color; 245 if (ColorUtilsFromCompat.calculateContrast(fg, bg) >= minRatio) { 246 return color; 247 } 248 249 double[] lab = new double[3]; 250 ColorUtilsFromCompat.colorToLAB(findFg ? fg : bg, lab); 251 252 double low = 0, high = lab[0]; 253 final double a = lab[1], b = lab[2]; 254 for (int i = 0; i < 15 && high - low > 0.00001; i++) { 255 final double l = (low + high) / 2; 256 if (findFg) { 257 fg = ColorUtilsFromCompat.LABToColor(l, a, b); 258 } else { 259 bg = ColorUtilsFromCompat.LABToColor(l, a, b); 260 } 261 if (ColorUtilsFromCompat.calculateContrast(fg, bg) > minRatio) { 262 low = l; 263 } else { 264 high = l; 265 } 266 } 267 return ColorUtilsFromCompat.LABToColor(low, a, b); 268 } 269 270 /** 271 * Finds a suitable color such that there's enough contrast. 272 * 273 * @param color the color to start searching from. 274 * @param other the color to ensure contrast against. Assumed to be darker than {@param color} 275 * @param findFg if true, we assume {@param color} is a foreground, otherwise a background. 276 * @param minRatio the minimum contrast ratio required. 277 * @return a color with the same hue as {@param color}, potentially darkened to meet the 278 * contrast ratio. 279 */ 280 public static int findContrastColorAgainstDark(int color, int other, boolean findFg, 281 double minRatio) { 282 int fg = findFg ? color : other; 283 int bg = findFg ? other : color; 284 if (ColorUtilsFromCompat.calculateContrast(fg, bg) >= minRatio) { 285 return color; 286 } 287 288 double[] lab = new double[3]; 289 ColorUtilsFromCompat.colorToLAB(findFg ? fg : bg, lab); 290 291 double low = lab[0], high = 100; 292 final double a = lab[1], b = lab[2]; 293 for (int i = 0; i < 15 && high - low > 0.00001; i++) { 294 final double l = (low + high) / 2; 295 if (findFg) { 296 fg = ColorUtilsFromCompat.LABToColor(l, a, b); 297 } else { 298 bg = ColorUtilsFromCompat.LABToColor(l, a, b); 299 } 300 if (ColorUtilsFromCompat.calculateContrast(fg, bg) > minRatio) { 301 high = l; 302 } else { 303 low = l; 304 } 305 } 306 return ColorUtilsFromCompat.LABToColor(high, a, b); 307 } 308 309 /** 310 * Finds a text color with sufficient contrast over bg that has the same hue as the original 311 * color, assuming it is for large text. 312 */ 313 public static int ensureLargeTextContrast(int color, int bg) { 314 return findContrastColor(color, bg, true, 3); 315 } 316 317 /** 318 * Finds a text color with sufficient contrast over bg that has the same hue as the original 319 * color. 320 */ 321 private static int ensureTextContrast(int color, int bg) { 322 return findContrastColor(color, bg, true, 4.5); 323 } 324 325 /** Finds a background color for a text view with given text color and hint text color, that 326 * has the same hue as the original color. 327 */ 328 public static int ensureTextBackgroundColor(int color, int textColor, int hintColor) { 329 color = findContrastColor(color, hintColor, false, 3.0); 330 return findContrastColor(color, textColor, false, 4.5); 331 } 332 333 private static String contrastChange(int colorOld, int colorNew, int bg) { 334 return String.format("from %.2f:1 to %.2f:1", 335 ColorUtilsFromCompat.calculateContrast(colorOld, bg), 336 ColorUtilsFromCompat.calculateContrast(colorNew, bg)); 337 } 338 339 /** 340 * Resolves {@param color} to an actual color if it is {@link Notification#COLOR_DEFAULT} 341 */ 342 public static int resolveColor(Context context, int color) { 343 if (color == Notification.COLOR_DEFAULT) { 344 return context.getColor(com.android.internal.R.color.notification_icon_default_color); 345 } 346 return color; 347 } 348 349 /** 350 * Resolves a Notification's color such that it has enough contrast to be used as the 351 * color for the Notification's action and header text. 352 * 353 * @param notificationColor the color of the notification or {@link Notification#COLOR_DEFAULT} 354 * @return a color of the same hue with enough contrast against the backgrounds. 355 */ 356 public static int resolveContrastColor(Context context, int notificationColor) { 357 final int resolvedColor = resolveColor(context, notificationColor); 358 359 final int actionBg = context.getColor( 360 com.android.internal.R.color.notification_action_list); 361 final int notiBg = context.getColor( 362 com.android.internal.R.color.notification_material_background_color); 363 364 int color = resolvedColor; 365 color = NotificationColorUtil.ensureLargeTextContrast(color, actionBg); 366 color = NotificationColorUtil.ensureTextContrast(color, notiBg); 367 368 if (color != resolvedColor) { 369 if (DEBUG){ 370 Log.w(TAG, String.format( 371 "Enhanced contrast of notification for %s %s (over action)" 372 + " and %s (over background) by changing #%s to %s", 373 context.getPackageName(), 374 NotificationColorUtil.contrastChange(resolvedColor, color, actionBg), 375 NotificationColorUtil.contrastChange(resolvedColor, color, notiBg), 376 Integer.toHexString(resolvedColor), Integer.toHexString(color))); 377 } 378 } 379 return color; 380 } 381 382 /** 383 * Lighten a color by a specified value 384 * @param baseColor the base color to lighten 385 * @param amount the amount to lighten the color from 0 to 100. This corresponds to the L 386 * increase in the LAB color space. 387 * @return the lightened color 388 */ 389 public static int lightenColor(int baseColor, int amount) { 390 final double[] result = ColorUtilsFromCompat.getTempDouble3Array(); 391 ColorUtilsFromCompat.colorToLAB(baseColor, result); 392 result[0] = Math.min(100, result[0] + amount); 393 return ColorUtilsFromCompat.LABToColor(result[0], result[1], result[2]); 394 } 395 396 /** 397 * Framework copy of functions needed from android.support.v4.graphics.ColorUtils. 398 */ 399 private static class ColorUtilsFromCompat { 400 private static final double XYZ_WHITE_REFERENCE_X = 95.047; 401 private static final double XYZ_WHITE_REFERENCE_Y = 100; 402 private static final double XYZ_WHITE_REFERENCE_Z = 108.883; 403 private static final double XYZ_EPSILON = 0.008856; 404 private static final double XYZ_KAPPA = 903.3; 405 406 private static final int MIN_ALPHA_SEARCH_MAX_ITERATIONS = 10; 407 private static final int MIN_ALPHA_SEARCH_PRECISION = 1; 408 409 private static final ThreadLocal<double[]> TEMP_ARRAY = new ThreadLocal<>(); 410 411 private ColorUtilsFromCompat() {} 412 413 /** 414 * Composite two potentially translucent colors over each other and returns the result. 415 */ 416 public static int compositeColors(@ColorInt int foreground, @ColorInt int background) { 417 int bgAlpha = Color.alpha(background); 418 int fgAlpha = Color.alpha(foreground); 419 int a = compositeAlpha(fgAlpha, bgAlpha); 420 421 int r = compositeComponent(Color.red(foreground), fgAlpha, 422 Color.red(background), bgAlpha, a); 423 int g = compositeComponent(Color.green(foreground), fgAlpha, 424 Color.green(background), bgAlpha, a); 425 int b = compositeComponent(Color.blue(foreground), fgAlpha, 426 Color.blue(background), bgAlpha, a); 427 428 return Color.argb(a, r, g, b); 429 } 430 431 private static int compositeAlpha(int foregroundAlpha, int backgroundAlpha) { 432 return 0xFF - (((0xFF - backgroundAlpha) * (0xFF - foregroundAlpha)) / 0xFF); 433 } 434 435 private static int compositeComponent(int fgC, int fgA, int bgC, int bgA, int a) { 436 if (a == 0) return 0; 437 return ((0xFF * fgC * fgA) + (bgC * bgA * (0xFF - fgA))) / (a * 0xFF); 438 } 439 440 /** 441 * Returns the luminance of a color as a float between {@code 0.0} and {@code 1.0}. 442 * <p>Defined as the Y component in the XYZ representation of {@code color}.</p> 443 */ 444 @FloatRange(from = 0.0, to = 1.0) 445 public static double calculateLuminance(@ColorInt int color) { 446 final double[] result = getTempDouble3Array(); 447 colorToXYZ(color, result); 448 // Luminance is the Y component 449 return result[1] / 100; 450 } 451 452 /** 453 * Returns the contrast ratio between {@code foreground} and {@code background}. 454 * {@code background} must be opaque. 455 * <p> 456 * Formula defined 457 * <a href="http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef">here</a>. 458 */ 459 public static double calculateContrast(@ColorInt int foreground, @ColorInt int background) { 460 if (Color.alpha(background) != 255) { 461 throw new IllegalArgumentException("background can not be translucent: #" 462 + Integer.toHexString(background)); 463 } 464 if (Color.alpha(foreground) < 255) { 465 // If the foreground is translucent, composite the foreground over the background 466 foreground = compositeColors(foreground, background); 467 } 468 469 final double luminance1 = calculateLuminance(foreground) + 0.05; 470 final double luminance2 = calculateLuminance(background) + 0.05; 471 472 // Now return the lighter luminance divided by the darker luminance 473 return Math.max(luminance1, luminance2) / Math.min(luminance1, luminance2); 474 } 475 476 /** 477 * Convert the ARGB color to its CIE Lab representative components. 478 * 479 * @param color the ARGB color to convert. The alpha component is ignored 480 * @param outLab 3-element array which holds the resulting LAB components 481 */ 482 public static void colorToLAB(@ColorInt int color, @NonNull double[] outLab) { 483 RGBToLAB(Color.red(color), Color.green(color), Color.blue(color), outLab); 484 } 485 486 /** 487 * Convert RGB components to its CIE Lab representative components. 488 * 489 * <ul> 490 * <li>outLab[0] is L [0 ...100)</li> 491 * <li>outLab[1] is a [-128...127)</li> 492 * <li>outLab[2] is b [-128...127)</li> 493 * </ul> 494 * 495 * @param r red component value [0..255] 496 * @param g green component value [0..255] 497 * @param b blue component value [0..255] 498 * @param outLab 3-element array which holds the resulting LAB components 499 */ 500 public static void RGBToLAB(@IntRange(from = 0x0, to = 0xFF) int r, 501 @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b, 502 @NonNull double[] outLab) { 503 // First we convert RGB to XYZ 504 RGBToXYZ(r, g, b, outLab); 505 // outLab now contains XYZ 506 XYZToLAB(outLab[0], outLab[1], outLab[2], outLab); 507 // outLab now contains LAB representation 508 } 509 510 /** 511 * Convert the ARGB color to it's CIE XYZ representative components. 512 * 513 * <p>The resulting XYZ representation will use the D65 illuminant and the CIE 514 * 2° Standard Observer (1931).</p> 515 * 516 * <ul> 517 * <li>outXyz[0] is X [0 ...95.047)</li> 518 * <li>outXyz[1] is Y [0...100)</li> 519 * <li>outXyz[2] is Z [0...108.883)</li> 520 * </ul> 521 * 522 * @param color the ARGB color to convert. The alpha component is ignored 523 * @param outXyz 3-element array which holds the resulting LAB components 524 */ 525 public static void colorToXYZ(@ColorInt int color, @NonNull double[] outXyz) { 526 RGBToXYZ(Color.red(color), Color.green(color), Color.blue(color), outXyz); 527 } 528 529 /** 530 * Convert RGB components to it's CIE XYZ representative components. 531 * 532 * <p>The resulting XYZ representation will use the D65 illuminant and the CIE 533 * 2° Standard Observer (1931).</p> 534 * 535 * <ul> 536 * <li>outXyz[0] is X [0 ...95.047)</li> 537 * <li>outXyz[1] is Y [0...100)</li> 538 * <li>outXyz[2] is Z [0...108.883)</li> 539 * </ul> 540 * 541 * @param r red component value [0..255] 542 * @param g green component value [0..255] 543 * @param b blue component value [0..255] 544 * @param outXyz 3-element array which holds the resulting XYZ components 545 */ 546 public static void RGBToXYZ(@IntRange(from = 0x0, to = 0xFF) int r, 547 @IntRange(from = 0x0, to = 0xFF) int g, @IntRange(from = 0x0, to = 0xFF) int b, 548 @NonNull double[] outXyz) { 549 if (outXyz.length != 3) { 550 throw new IllegalArgumentException("outXyz must have a length of 3."); 551 } 552 553 double sr = r / 255.0; 554 sr = sr < 0.04045 ? sr / 12.92 : Math.pow((sr + 0.055) / 1.055, 2.4); 555 double sg = g / 255.0; 556 sg = sg < 0.04045 ? sg / 12.92 : Math.pow((sg + 0.055) / 1.055, 2.4); 557 double sb = b / 255.0; 558 sb = sb < 0.04045 ? sb / 12.92 : Math.pow((sb + 0.055) / 1.055, 2.4); 559 560 outXyz[0] = 100 * (sr * 0.4124 + sg * 0.3576 + sb * 0.1805); 561 outXyz[1] = 100 * (sr * 0.2126 + sg * 0.7152 + sb * 0.0722); 562 outXyz[2] = 100 * (sr * 0.0193 + sg * 0.1192 + sb * 0.9505); 563 } 564 565 /** 566 * Converts a color from CIE XYZ to CIE Lab representation. 567 * 568 * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE 569 * 2° Standard Observer (1931).</p> 570 * 571 * <ul> 572 * <li>outLab[0] is L [0 ...100)</li> 573 * <li>outLab[1] is a [-128...127)</li> 574 * <li>outLab[2] is b [-128...127)</li> 575 * </ul> 576 * 577 * @param x X component value [0...95.047) 578 * @param y Y component value [0...100) 579 * @param z Z component value [0...108.883) 580 * @param outLab 3-element array which holds the resulting Lab components 581 */ 582 public static void XYZToLAB(@FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_X) double x, 583 @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Y) double y, 584 @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Z) double z, 585 @NonNull double[] outLab) { 586 if (outLab.length != 3) { 587 throw new IllegalArgumentException("outLab must have a length of 3."); 588 } 589 x = pivotXyzComponent(x / XYZ_WHITE_REFERENCE_X); 590 y = pivotXyzComponent(y / XYZ_WHITE_REFERENCE_Y); 591 z = pivotXyzComponent(z / XYZ_WHITE_REFERENCE_Z); 592 outLab[0] = Math.max(0, 116 * y - 16); 593 outLab[1] = 500 * (x - y); 594 outLab[2] = 200 * (y - z); 595 } 596 597 /** 598 * Converts a color from CIE Lab to CIE XYZ representation. 599 * 600 * <p>The resulting XYZ representation will use the D65 illuminant and the CIE 601 * 2° Standard Observer (1931).</p> 602 * 603 * <ul> 604 * <li>outXyz[0] is X [0 ...95.047)</li> 605 * <li>outXyz[1] is Y [0...100)</li> 606 * <li>outXyz[2] is Z [0...108.883)</li> 607 * </ul> 608 * 609 * @param l L component value [0...100) 610 * @param a A component value [-128...127) 611 * @param b B component value [-128...127) 612 * @param outXyz 3-element array which holds the resulting XYZ components 613 */ 614 public static void LABToXYZ(@FloatRange(from = 0f, to = 100) final double l, 615 @FloatRange(from = -128, to = 127) final double a, 616 @FloatRange(from = -128, to = 127) final double b, 617 @NonNull double[] outXyz) { 618 final double fy = (l + 16) / 116; 619 final double fx = a / 500 + fy; 620 final double fz = fy - b / 200; 621 622 double tmp = Math.pow(fx, 3); 623 final double xr = tmp > XYZ_EPSILON ? tmp : (116 * fx - 16) / XYZ_KAPPA; 624 final double yr = l > XYZ_KAPPA * XYZ_EPSILON ? Math.pow(fy, 3) : l / XYZ_KAPPA; 625 626 tmp = Math.pow(fz, 3); 627 final double zr = tmp > XYZ_EPSILON ? tmp : (116 * fz - 16) / XYZ_KAPPA; 628 629 outXyz[0] = xr * XYZ_WHITE_REFERENCE_X; 630 outXyz[1] = yr * XYZ_WHITE_REFERENCE_Y; 631 outXyz[2] = zr * XYZ_WHITE_REFERENCE_Z; 632 } 633 634 /** 635 * Converts a color from CIE XYZ to its RGB representation. 636 * 637 * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE 638 * 2° Standard Observer (1931).</p> 639 * 640 * @param x X component value [0...95.047) 641 * @param y Y component value [0...100) 642 * @param z Z component value [0...108.883) 643 * @return int containing the RGB representation 644 */ 645 @ColorInt 646 public static int XYZToColor(@FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_X) double x, 647 @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Y) double y, 648 @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Z) double z) { 649 double r = (x * 3.2406 + y * -1.5372 + z * -0.4986) / 100; 650 double g = (x * -0.9689 + y * 1.8758 + z * 0.0415) / 100; 651 double b = (x * 0.0557 + y * -0.2040 + z * 1.0570) / 100; 652 653 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : 12.92 * r; 654 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : 12.92 * g; 655 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1 / 2.4) - 0.055 : 12.92 * b; 656 657 return Color.rgb( 658 constrain((int) Math.round(r * 255), 0, 255), 659 constrain((int) Math.round(g * 255), 0, 255), 660 constrain((int) Math.round(b * 255), 0, 255)); 661 } 662 663 /** 664 * Converts a color from CIE Lab to its RGB representation. 665 * 666 * @param l L component value [0...100] 667 * @param a A component value [-128...127] 668 * @param b B component value [-128...127] 669 * @return int containing the RGB representation 670 */ 671 @ColorInt 672 public static int LABToColor(@FloatRange(from = 0f, to = 100) final double l, 673 @FloatRange(from = -128, to = 127) final double a, 674 @FloatRange(from = -128, to = 127) final double b) { 675 final double[] result = getTempDouble3Array(); 676 LABToXYZ(l, a, b, result); 677 return XYZToColor(result[0], result[1], result[2]); 678 } 679 680 private static int constrain(int amount, int low, int high) { 681 return amount < low ? low : (amount > high ? high : amount); 682 } 683 684 private static double pivotXyzComponent(double component) { 685 return component > XYZ_EPSILON 686 ? Math.pow(component, 1 / 3.0) 687 : (XYZ_KAPPA * component + 16) / 116; 688 } 689 690 public static double[] getTempDouble3Array() { 691 double[] result = TEMP_ARRAY.get(); 692 if (result == null) { 693 result = new double[3]; 694 TEMP_ARRAY.set(result); 695 } 696 return result; 697 } 698 699 } 700} 701