1

駐車場アイコンをプログラムで描画して、マップ上のアイテム化されたオーバーレイのドローアブルとして配置しようとしています。

アイコンは、中央に白い「P」が付いた青い正方形で構成されており、さまざまな駐車タイプを示すために正方形の色をプログラムで変更したいと考えています。

drawRectとdrawTextを使用してキャンバス経由で作成しようとしましたが、テキストを正方形の中央に配置する簡単な方法が見つからず、キャンバスを座標の中央に配置する方法が見つかりません-左上から固定したい手の角。

または、XML レイアウトを作成してドローアブルに変換しようとしましたが、これも達成できません。

私が達成しようとしていることに対するエレガントな解決策はありますか?

4

2 に答える 2

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;
    }
}
于 2012-03-30T01:57:03.627 に答える
0

いくつかの png 画像を作成して に配置しres\drawableます。色が 5 つ以上ある場合は、使用する色を減らすことを検討してください。ユーザーにとっては紛らわしいです。

于 2012-03-23T01:00:36.910 に答える