gpt4 book ai didi

java - libgdx 中的居中对齐文本

转载 作者:太空狗 更新时间:2023-10-29 14:02:02 24 4
gpt4 key购买 nike

我刚刚开始使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com