Home | History | Annotate | Download | only in colorpicker
      1 /*
      2  * Copyright (C) 2013 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.colorpicker;
     18 
     19 import android.graphics.Color;
     20 import android.graphics.PorterDuff;
     21 import android.graphics.drawable.Drawable;
     22 import android.graphics.drawable.LayerDrawable;
     23 
     24 /**
     25  * A drawable which sets its color filter to a color specified by the user, and changes to a
     26  * slightly darker color when pressed or focused.
     27  */
     28 public class ColorStateDrawable extends LayerDrawable {
     29 
     30     private static final float PRESSED_STATE_MULTIPLIER = 0.70f;
     31 
     32     private int mColor;
     33 
     34     public ColorStateDrawable(Drawable[] layers, int color) {
     35         super(layers);
     36         mColor = color;
     37     }
     38 
     39     @Override
     40     protected boolean onStateChange(int[] states) {
     41         boolean pressedOrFocused = false;
     42         for (int state : states) {
     43             if (state == android.R.attr.state_pressed || state == android.R.attr.state_focused) {
     44                 pressedOrFocused = true;
     45                 break;
     46             }
     47         }
     48 
     49         if (pressedOrFocused) {
     50             super.setColorFilter(getPressedColor(mColor), PorterDuff.Mode.SRC_ATOP);
     51         } else {
     52             super.setColorFilter(mColor, PorterDuff.Mode.SRC_ATOP);
     53         }
     54 
     55         return super.onStateChange(states);
     56     }
     57 
     58     /**
     59      * Given a particular color, adjusts its value by a multiplier.
     60      */
     61     private static int getPressedColor(int color) {
     62         float[] hsv = new float[3];
     63         Color.colorToHSV(color, hsv);
     64         hsv[2] = hsv[2] * PRESSED_STATE_MULTIPLIER;
     65         return Color.HSVToColor(hsv);
     66     }
     67 
     68     @Override
     69     public boolean isStateful() {
     70         return true;
     71     }
     72 }
     73