Home | History | Annotate | Download | only in graphics
      1 /*
      2  * Copyright (C) 2016 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 package com.android.launcher3.graphics;
     17 
     18 import android.content.Context;
     19 import android.graphics.Canvas;
     20 import android.graphics.Paint;
     21 import android.graphics.Paint.FontMetricsInt;
     22 import android.graphics.drawable.Drawable;
     23 import android.text.style.DynamicDrawableSpan;
     24 
     25 /**
     26  * {@link DynamicDrawableSpan} which draws a drawable tinted with the current paint color.
     27  */
     28 public class TintedDrawableSpan extends DynamicDrawableSpan {
     29 
     30     private final Drawable mDrawable;
     31     private int mOldTint;
     32 
     33     public TintedDrawableSpan(Context context, int resourceId) {
     34         super(ALIGN_BOTTOM);
     35         mDrawable = context.getDrawable(resourceId);
     36         mOldTint = 0;
     37         mDrawable.setTint(0);
     38     }
     39 
     40     @Override
     41     public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
     42         fm = fm == null ? paint.getFontMetricsInt() : fm;
     43         int iconSize = fm.bottom - fm.top;
     44         mDrawable.setBounds(0, 0, iconSize, iconSize);
     45         return super.getSize(paint, text, start, end, fm);
     46     }
     47 
     48     @Override
     49     public void draw(Canvas canvas, CharSequence text,
     50             int start, int end, float x, int top, int y, int bottom, Paint paint) {
     51         int color = paint.getColor();
     52         if (mOldTint != color) {
     53             mOldTint = color;
     54             mDrawable.setTint(mOldTint);
     55         }
     56         super.draw(canvas, text, start, end, x, top, y, bottom, paint);
     57     }
     58 
     59     @Override
     60     public Drawable getDrawable() {
     61         return mDrawable;
     62     }
     63 }
     64