我正在尝试以编程方式绘制一个停车图标,作为地图上逐项列表的可绘制对象。
图标由一个蓝色方块组成,中间有一个白色的“P”,我想以编程方式更改方块的颜色,以表示不同的停车类型。
我尝试使用drawRect& amp; drawText但我找不到一种简单的方法将文本居中在广场上,我找不到将画布置于坐标中心的方法 - 它一直希望从左上角锚定。
我已经尝试过创建一个XML布局来转换为drawable,但也无法实现。
对于我想要实现的目标,是否有优雅的解决方案?
答案 0 :(得分:3)
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;
}
}
答案 1 :(得分:0)
制作几张png图片&把它们放在res\drawable
中,如果你有超过5种颜色,那么考虑少用。这让用户感到困惑。