在libgdx中如何居中对齐文本

3

我刚开始接触LibGdx,已经知道如何在其中居中文本。现在我遇到了将文本居中对齐的问题。请问有人可以帮忙吗?我已经附上了我的居中代码。先谢谢您。

package com.tutorials.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class TextDemo extends ApplicationAdapter {
    SpriteBatch batch;
    BitmapFont font;
    String myText;
    GlyphLayout layout = new GlyphLayout();

    @Override
    public void create () {
        batch = new SpriteBatch();
        font = new BitmapFont(Gdx.files.internal("myFont.fnt"));
        myText = "I took one, one cause you left me\n"
               + "Two, two for my family\n"
               + "Three, three for my heartache";
        layout.setText(font,myText);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        float x = Gdx.graphics.getWidth()/2 - layout.width/2;
        float y = Gdx.graphics.getHeight()/2 + layout.height/2;

        batch.begin();
        font.draw(batch,layout,x,y);//Center Text
        batch.end();
}

你能澄清你的意思吗?你已经居中了。将其“对齐”的区别是什么? - Tenfour04
如果您想在Microsoft Word中居中对齐一个段落,那么它应该是什么样子的,这是非常重要的。 - Jonathan Lopez
我认为Libgdx不支持这个。 - Tenfour04
2个回答

2
您可以使用以下的setText()方法,将targetWidth设置为屏幕宽度,Aligh.center,并将wrap设置为true。同时,将x = 0,以便文本在整个屏幕上居中显示。
import com.badlogic.gdx.graphics.g2d.GlyphLayout;

public void setText(BitmapFont font,
                java.lang.CharSequence str,
                Color color,
                float targetWidth,
                int halign,
                boolean wrap)

更新的示例:

@Override
public void create () {
    batch = new SpriteBatch();
    font = new BitmapFont(Gdx.files.internal("myFont.fnt"));
    myText = "I took one, one cause you left me\n"
           + "Two, two for my family\n"
           + "Three, three for my heartache";
    layout.setText(font,myText,Color.BLACK,Gdx.graphics.getWidth(),Align.center,true);
}

@Override
public void render () {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    float x = 0;
    float y = Gdx.graphics.getHeight()/2 + layout.height/2;

    batch.begin();
    font.draw(batch,layout,x,y);//Center Text
    batch.end();
}

0

不要使用font.draw方法,改用以下方法...

public TextBounds drawMultiLine (Batch batch, CharSequence str, float x, float y, float alignmentWidth, HAlignment alignment)

alignmentWidth是你希望文本占用的最大宽度。超过这个宽度,文本将换行。如果不想换行,请将其设置为非常高的值。

'alignment'是关键,它接受一个HAlignment枚举,可以是LEFTRIGHTCENTER

batchstrxy参数与你已经在做的相同。


我尝试了那种方法,但它没有起作用。我认为那种方法已经过时了。 - Jonathan Lopez
哦!对不起,我可能查看了旧版本。我稍后会找到当前的等效版本。 - Phil Anderson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接