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 } 38 39 @Override 40 public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) { 41 fm = fm == null ? paint.getFontMetricsInt() : fm; 42 int iconSize = fm.bottom - fm.top; 43 mDrawable.setBounds(0, 0, iconSize, iconSize); 44 return super.getSize(paint, text, start, end, fm); 45 } 46 47 @Override 48 public void draw(Canvas canvas, CharSequence text, 49 int start, int end, float x, int top, int y, int bottom, Paint paint) { 50 int color = paint.getColor(); 51 if (mOldTint != color) { 52 mOldTint = color; 53 mDrawable.setTint(mOldTint); 54 } 55 super.draw(canvas, text, start, end, x, top, y, bottom, paint); 56 } 57 58 @Override 59 public Drawable getDrawable() { 60 return mDrawable; 61 } 62 } 63