2 * Copyright (C) 2017 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.launcher3.graphics;
19 import android.graphics.Color;
20 import android.support.v4.graphics.ColorUtils;
23 * Contains colors based on the dominant color of an icon.
25 public class IconPalette {
27 public int backgroundColor;
29 public int secondaryColor;
31 public static IconPalette fromDominantColor(int dominantColor) {
32 IconPalette palette = new IconPalette();
33 palette.backgroundColor = getMutedColor(dominantColor);
34 palette.textColor = getTextColorForBackground(palette.backgroundColor);
35 palette.secondaryColor = getLowContrastColor(palette.backgroundColor);
39 private static int getMutedColor(int color) {
40 int alpha = (int) (255 * 0.15f);
41 return ColorUtils.compositeColors(ColorUtils.setAlphaComponent(color, alpha), Color.WHITE);
44 private static int getTextColorForBackground(int backgroundColor) {
45 return getLighterOrDarkerVersionOfColor(backgroundColor, 3f);
48 private static int getLowContrastColor(int color) {
49 return getLighterOrDarkerVersionOfColor(color, 1.5f);
52 private static int getLighterOrDarkerVersionOfColor(int color, float contrastRatio) {
53 int whiteMinAlpha = ColorUtils.calculateMinimumAlpha(Color.WHITE, color, contrastRatio);
54 int blackMinAlpha = ColorUtils.calculateMinimumAlpha(Color.BLACK, color, contrastRatio);
55 int translucentWhiteOrBlack;
56 if (whiteMinAlpha >= 0) {
57 translucentWhiteOrBlack = ColorUtils.setAlphaComponent(Color.WHITE, whiteMinAlpha);
58 } else if (blackMinAlpha >= 0) {
59 translucentWhiteOrBlack = ColorUtils.setAlphaComponent(Color.BLACK, blackMinAlpha);
61 translucentWhiteOrBlack = Color.WHITE;
63 return ColorUtils.compositeColors(translucentWhiteOrBlack, color);