Android 图形库,正在创建消息框

Android Graphics Libraries, creating a message box

我想做的很简单。我希望能够在屏幕上绘制一个消息框,将框的高度包裹到其中的文本大小。

我正在使用 android 的 canvas 对象来执行此操作,但我不知道如何使用此库来完成此操作。

我正在尝试重现:

我希望能够更改横幅内的文本并使其包裹高度。谁能告诉我这是怎么做到的?

编辑

这是我目前拥有的。有很多数学运算,它几乎不能用于一种分辨率,更不用说所有这些了。

        int x = (int) SCREEN_WIDTH / 2, y = (int) ((SCREEN_HEIGHT / 1.3f) + messageBox.getPaint().getTextSize() + 10);
        String[] message = messageBox.getMessage().split("\n");
        for (String line: message)
        {
            System.out.println(message.length);
              canvas.drawText(line, x, y, messageBox.getPaint());
              y += -messageBox.getPaint().ascent() + messageBox.getPaint().descent();
        }

private void resizeBox() {
    if(message == null) 
        return;

    String[] msg = message.split("\n");

    this.bottom += (this.getPaint().getTextSize() + 10) * msg.length;

}

I am not using XML within my application

有人给你的印象是 using XML within [an Android] application 是一个 选择 吗?

不是。

如果您使用您可以随意使用的工具,您想要完成的工作只需 5 分钟。

There must be an easy way to do this or else why do people use android =.=

不知道你这是什么意思。

I just draw RectF's and draw Text using the canvas

好的,那么:

在此图像中,原始文本为:

"Oops!\n\n" +
"Highscore: 59\n\n" +
"Your score: 12\n\n" +
"Better luck next time :(\n" +
"Touch the red box to try again."

如您所见,线宽很适合给定的 space - 线不换行。

在下图中,最后一个换行符 (\n) 已被移除,以举例说明当线宽不适合屏幕宽度时会发生什么:

第二张图片的文字是:

"Oops!\n\n" +
"Highscore: 59\n\n" +
"Your score: 12\n\n" +
"Better luck next time :( Touch the red box to try again."

我们使用 StaticLayout 在此处呈现文本:Link

StaticLayout 负责在 Canvas 上绘制文本所需的所有细节。这是 onDraw(Canvas) 的样子:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (mStaticLayout == null) {
        mStaticLayout = new StaticLayout(mText, mTextPaint, getWidth(),
            Layout.Alignment.ALIGN_CENTER, 1f, 0f, true);
    }

    canvas.save();

    // Go to where we need to draw this text
    canvas.translate(0, getHeight() / 2 - mStaticLayout.getHeight() / 2);

    // 'mBoundingBoxPaint' is an instance of 'Paint'
    mBoundingBoxPaint.setColor(Color.BLACK);
    mBoundingBoxPaint.setAlpha(100);

    // Draw the bounding box *before* drawing the text
    canvas.drawRect(0, /* paddingTop */-50, mStaticLayout.getWidth(),
                      mStaticLayout.getHeight() + /* paddingBottom */50, 
                      mBoundingBoxPaint);

    // Draw the text
    mStaticLayout.draw(canvas);
    canvas.restore();
}

您可以在上面给出的 link 中阅读有关使用 StaticLayout 的更多信息。或者,您可以查看其源代码以更好地了解它如何呈现文本。