public class TextDrawable extends Drawable {
private final static int TEXT_PADDING = 3;
private final static int ROUNDED_RECT_RADIUS = 5;
private final String text;
private final Paint textPaint;
private final Rect textBounds;
private final Paint bgPaint;
private final RectF bgBounds;
public TextDrawable(String text, String backgroundColor, int textHeight) {
this.text = text;
// Text
this.textPaint = new Paint();
this.textBounds = new Rect();
textPaint.setColor(Color.WHITE);
textPaint.setARGB(255, 255, 255, 255);
textPaint.setAntiAlias(true);
textPaint.setSubpixelText(true);
textPaint.setTextAlign(Paint.Align.CENTER); // Important to centre horizontally in the background RectF
textPaint.setTextSize(textHeight);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
// Map textPaint to a Rect in order to get its true height
// ... a bit long-winded I know but unfortunately getTextSize does not seem to give a true height!
textPaint.getTextBounds(text, 0, text.length(), textBounds);
// Background
this.bgPaint = new Paint();
bgPaint.setAntiAlias(true);
bgPaint.setColor(Color.parseColor(backgroundColor));
float rectHeight = TEXT_PADDING * 2 + textHeight;
float rectWidth = TEXT_PADDING * 2 + textPaint.measureText(text);
//float rectWidth = TEXT_PADDING * 2 + textHeight; // Square (alternative)
// Create the background - use negative start x/y coordinates to centre align the icon
this.bgBounds = new RectF(rectWidth/-2, rectHeight/-2, rectWidth/2, rectHeight/2);
}
@Override
public void draw(Canvas canvas) {
canvas.drawRoundRect(bgBounds, ROUNDED_RECT_RADIUS, ROUNDED_RECT_RADIUS, bgPaint);
// Position the text in the horizontal/vertical centre of the background RectF
canvas.drawText(text, 0, (textBounds.bottom - textBounds.top)/2, textPaint);
}
@Override
public void setAlpha(int alpha) {
bgPaint.setAlpha(alpha);
textPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter cf) {
bgPaint.setColorFilter(cf);
textPaint.setColorFilter(cf);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
是的我同意多於5種顏色會讓用戶感到困惑 - 我打算讓每種停車類型都可以在應用程序的設置中單獨打開/關閉。它也將與其他字母一起用於表示其他地圖特徵(例如,馬桶,飲水機等)。我真的試圖避免重複使用不同顏色的圖標 - 特別是因爲它只是彩色背景上的文字。 – Azzamatazz 2012-03-23 01:22:59
您當然可以在代碼中創建自己的圖標,但使用真實的圖像編輯器可以更容易地完成它,並且最終可能會獲得更好的效果。此外,替換圖像很容易,而代碼不是。並且在代碼中創建圖像甚至需要花費更長時間才能加載圖標,因此您的應用可能會變慢。我建議你使用PNG,除非你有很大的圖標或想像整個中文字母的圖標。 – zapl 2012-03-23 08:09:05