在libgdx中居中对齐文本

时间:2016-01-21 03:31:19

标签: java android libgdx

我刚刚开始使用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();
}

2 个答案:

答案 0 :(得分:1)

您可以使用以下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();
}

答案 1 :(得分:0)

而不是使用font.draw方法,而是使用以下方法......

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

alignmentWidth是您希望文本占用的最大宽度。不止于此,它将包装。如果你不想包装,请将它设置为愚蠢的高度。

'alignment'是关键,它采用HAlignment枚举,可以是LEFTRIGHTCENTER

batchstrxy参数与您现在的参数相同。

相关问题