1 /* 2 * Copyright (C) 2010 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.gallery3d.ui; 18 19 import android.graphics.Bitmap; 20 import android.graphics.Canvas; 21 import android.graphics.Color; 22 import android.graphics.Paint.FontMetricsInt; 23 import android.graphics.Typeface; 24 import android.text.TextPaint; 25 import android.text.TextUtils; 26 27 // StringTexture is a texture shows the content of a specified String. 28 // 29 // To create a StringTexture, use the newInstance() method and specify 30 // the String, the font size, and the color. 31 class StringTexture extends CanvasTexture { 32 private final String mText; 33 private final TextPaint mPaint; 34 private final FontMetricsInt mMetrics; 35 36 private StringTexture(String text, TextPaint paint, 37 FontMetricsInt metrics, int width, int height) { 38 super(width, height); 39 mText = text; 40 mPaint = paint; 41 mMetrics = metrics; 42 } 43 44 public static TextPaint getDefaultPaint(float textSize, int color) { 45 TextPaint paint = new TextPaint(); 46 paint.setTextSize(textSize); 47 paint.setAntiAlias(true); 48 paint.setColor(color); 49 paint.setShadowLayer(2f, 0f, 0f, Color.BLACK); 50 return paint; 51 } 52 53 public static StringTexture newInstance( 54 String text, float textSize, int color) { 55 return newInstance(text, getDefaultPaint(textSize, color)); 56 } 57 58 public static StringTexture newInstance( 59 String text, float textSize, int color, 60 float lengthLimit, boolean isBold) { 61 TextPaint paint = getDefaultPaint(textSize, color); 62 if (isBold) { 63 paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); 64 } 65 text = TextUtils.ellipsize( 66 text, paint, lengthLimit, TextUtils.TruncateAt.END).toString(); 67 return newInstance(text, paint); 68 } 69 70 private static StringTexture newInstance(String text, TextPaint paint) { 71 FontMetricsInt metrics = paint.getFontMetricsInt(); 72 int width = (int) Math.ceil(paint.measureText(text)); 73 int height = metrics.bottom - metrics.top; 74 // The texture size needs to be at least 1x1. 75 if (width <= 0) width = 1; 76 if (height <= 0) height = 1; 77 return new StringTexture(text, paint, metrics, width, height); 78 } 79 80 @Override 81 protected void onDraw(Canvas canvas, Bitmap backing) { 82 canvas.translate(0, -mMetrics.ascent); 83 canvas.drawText(mText, 0, 0, mPaint); 84 } 85 } 86