ColorFilterCache.java revision cf94c5fa8ae8edb7e26a623133207415ceeed187
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 * Helper class of mapping ColorFilter from a color with 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 ColorDimmer for a given color. Only r/g/b are used, alpha channel is ignored 34 * from parameter dimColor. 35 */ 36 public static ColorFilterCache getColorFilterCache(int dimColor) { 37 final int r = Color.red(dimColor); 38 final int g = Color.green(dimColor); 39 final int b = Color.blue(dimColor); 40 dimColor = Color.rgb(r, g, b); 41 ColorFilterCache colorDimmer = sColorToFiltersMap.get(dimColor); 42 if (colorDimmer == null) { 43 colorDimmer = new ColorFilterCache(r, g, b); 44 sColorToFiltersMap.put(dimColor, colorDimmer); 45 } 46 return colorDimmer; 47 } 48 49 private ColorFilterCache(int r, int g, int b) { 50 // Pre cache all Dim filter levels 51 for (int i = 0x00; i <= 0xFF; i++) { 52 int color = Color.argb(i, r, g, b); 53 mFilters[i] = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP); 54 } 55 } 56 57 /** 58 * Returns ColorFilter for a given level between 0 and 1. 59 */ 60 public ColorFilter getFilterForLevel(float level) { 61 if (level >= 0 && level <= 1.0) { 62 int filterIndex = (int) (0xFF * level); 63 return mFilters[filterIndex]; 64 } else { 65 return null; 66 } 67 } 68}