1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
12 * the License.
13 */
14package android.support.v17.leanback.graphics;
15
16import android.graphics.Color;
17import android.graphics.ColorFilter;
18import android.graphics.PorterDuff;
19import android.graphics.PorterDuffColorFilter;
20import android.util.SparseArray;
21
22/**
23 * Cache of {@link ColorFilter}s for a given color at different alpha levels.
24 */
25public final class ColorFilterCache {
26
27    private static final SparseArray<ColorFilterCache> sColorToFiltersMap =
28            new SparseArray<ColorFilterCache>();
29
30    private final PorterDuffColorFilter[] mFilters = new PorterDuffColorFilter[0x100];
31
32    /**
33     * Get a ColorDimmer for a given color.  Only the RGB values are used; the
34     * alpha channel is ignored in color. Subsequent calls to this method
35     * with the same color value will return the same cache.
36     *
37     * @param color The color to use for the color filters.
38     * @return A cache of ColorFilters at different alpha levels for the color.
39     */
40    public static ColorFilterCache getColorFilterCache(int color) {
41        final int r = Color.red(color);
42        final int g = Color.green(color);
43        final int b = Color.blue(color);
44        color = Color.rgb(r, g, b);
45        ColorFilterCache filters = sColorToFiltersMap.get(color);
46        if (filters == null) {
47            filters = new ColorFilterCache(r, g, b);
48            sColorToFiltersMap.put(color, filters);
49        }
50        return filters;
51    }
52
53    private ColorFilterCache(int r, int g, int b) {
54        // Pre cache all 256 filter levels
55        for (int i = 0x00; i <= 0xFF; i++) {
56            int color = Color.argb(i, r, g, b);
57            mFilters[i] = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP);
58        }
59    }
60
61    /**
62     * Returns a ColorFilter for a given alpha level between 0 and 1.0.
63     *
64     * @param level The alpha level the filter should apply.
65     * @return A ColorFilter at the alpha level for the color represented by the
66     *         cache.
67     */
68    public ColorFilter getFilterForLevel(float level) {
69        if (level >= 0 && level <= 1.0) {
70            int filterIndex = (int) (0xFF * level);
71            return mFilters[filterIndex];
72        } else {
73            return null;
74        }
75    }
76}
77