how to draw text with background color using canvas

后端 未结 4 2095
-上瘾入骨i
-上瘾入骨i 2021-02-19 16:37

I have some code where I\'m drawing my text on bitmap (canvas)

canvas.drawTextOnPath(Text, textPath[count], gipa, -10, text);

Please tell me,

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-19 17:16

    I believe this solution is better and more flexible than drawPath.

    Use this to calculate the size of the text background:

    private @NonNull Rect getTextBackgroundSize(float x, float y, @NonNull String text, @NonNull TextPaint paint) {
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        float halfTextLength = paint.measureText(text) / 2 + 5;
        return new Rect((int) (x - halfTextLength), (int) (y + fontMetrics.top), (int) (x + halfTextLength), (int) (y + fontMetrics.bottom));
    }
    

    Then draw the background as a Rect:

    Rect background = getTextBackgroundSize(x, y, text, textPaint);
    canvas.drawRect(background, bkgPaint);
    canvas.drawText(text, x, t, textPaint);
    

提交回复
热议问题