【问题标题】:Draw multi-line BitmapFont vertically centered绘制多行 BitmapFont 垂直居中
【发布时间】:2019-07-16 03:21:24
【问题描述】:

我希望将一些跨越几行的长包装文本居中在一个矩形(或其他任何东西)上,如下图所示(我不需要隐藏多余的文本,但这将是一个很大的优势非常感谢):

我已经能够使用如下单行文本实现垂直居中:

BitmapFont font = new BitmapFont();
String text = "Hello";
Rectangle bounds = new Rectangle(0, 0, 100, 100);

void render(SpriteBatch spriteBatch) {
    font.draw(
        spriteBatch,
        text,
        bounds.x,
        bounds.y + bounds.height / 2f + font.getLineHeight());
}

我知道有一个 BitmapFont.draw() 方法变体,可让您指定水平对齐方式、文本的目标宽度和换行标志,但我似乎找不到 vertically 多对齐方式- 行文本。

在过去,这可以通过 BitmapFont.getBounds() 和一些数学方法实现,但 LibGDX 1.9.9 中没有这种方法。

【问题讨论】:

    标签: libgdx text-rendering


    【解决方案1】:

    使用GlyphLayout 类,我们可以获得包裹文本的高度,我制作了一个辅助方法来将Rectangle 中的文本居中,提高了我们应用程序的主要render() 方法中代码的可读性/游戏:

    private static GlyphLayout glyphLayout = new GlyphLayout();
    public static void drawCentered(BitmapFont font, SpriteBatch spriteBatch,
                                        String text, Rectangle bounds) {
            glyphLayout.setText(font, text, Color.BLACK, bounds.width, Align.center, true);
            font.draw(
                    spriteBatch,
                    text,
                    bounds.x,
                    bounds.y + bounds.height / 2f + glyphLayout.height / 2f,
                    bounds.width,
                    Align.center,
                    true);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-10
      • 1970-01-01
      • 2019-03-09
      • 2014-02-09
      • 1970-01-01
      • 2013-10-15
      • 2011-05-04
      • 1970-01-01
      相关资源
      最近更新 更多