SimpleStringTexture.java revision f99dfe8549fb6c2c06c8cb7ca7d5eb33002c809e
1package com.cooliris.media; 2 3import android.graphics.Bitmap; 4import android.graphics.Canvas; 5import android.graphics.Color; 6import android.graphics.Paint; 7import android.graphics.Rect; 8import android.graphics.Typeface; 9 10public final class SimpleStringTexture extends Texture { 11 12 private final String mString; 13 private final StringTexture.Config mConfig; 14 private float mBaselineHeight = 0.0f; 15 16 SimpleStringTexture(String string, StringTexture.Config config) { 17 mString = string; 18 mConfig = config; 19 } 20 21 public float getBaselineHeight() { 22 return mBaselineHeight; 23 } 24 25 @Override 26 public boolean isCached() { 27 return true; 28 } 29 30 @Override 31 protected Bitmap load(RenderView view) { 32 // Configure paint. 33 StringTexture.Config config = mConfig; 34 Paint paint = new Paint(); 35 paint.setAntiAlias(true); 36 paint.setColor(Shared.argb(config.a, config.r, config.g, config.b)); 37 paint.setShadowLayer(config.shadowRadius, 0f, 0f, Color.BLACK); 38 paint.setTypeface(config.bold ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT); 39 paint.setTextSize(config.fontSize); 40 paint.setUnderlineText(config.underline); 41 paint.setStrikeThruText(config.strikeThrough); 42 if (config.italic) { 43 paint.setTextSkewX(-0.25f); 44 } 45 46 // Measure string. 47 String string = mString; 48 Rect bounds = new Rect(); 49 paint.getTextBounds(string, 0, string.length(), bounds); 50 51 // Get font metrics. 52 Paint.FontMetricsInt metrics = paint.getFontMetricsInt(); 53 int height = metrics.bottom - metrics.top; 54 55 // Draw string into bitmap with a 1px margin for anti-aliasing. 56 // Ensure baseline alignment with other strings of the same size. 57 int padding = 1 + config.shadowRadius; 58 Bitmap bitmap = Bitmap 59 .createBitmap(bounds.width() + padding + padding, height + padding + padding, Bitmap.Config.ARGB_8888); 60 Canvas canvas = new Canvas(bitmap); 61 canvas.translate(padding, padding - metrics.ascent); 62 canvas.drawText(string, 0, 0, paint); 63 64 mBaselineHeight = padding + metrics.bottom; 65 66 return bitmap; 67 } 68 69} 70