java - libgdx 中的居中对齐文本

标签 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();
}

最佳答案

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

关于java - libgdx 中的居中对齐文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34914924/

相关文章:

java - 在舞台上添加无限数量的 Actor (libGDX)

java - JOGL 1.x 未签名的小程序可能吗?

java - JacksonConverter 缺少 getObjectMapper() 方法

java - 无法在模拟器中启动 AVD。 VCPU 关闭请求

android - 如何在 setOnItemClickListener 上将 ListView 记录从 sqlite 显示到第二个 ListView

android - Firefox for Android native 应用程序图标(地址栏)

java - LibGDX FrameBuffer 缩放

java - UnknownHostException 尝试通过 Ektorp 连接到 Cloudant DB

java - 使用 Hibernate 调用实体方法

java - 60FPS 的滞后空项目