2016-01-21 53 views
3

我剛剛開始使用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(); 
} 
+0

你能澄清你是什麼意思?你已經集中它。中心「證明」它的區別是什麼? – Tenfour04

+0

如果您想以Microsoft Word爲中心對齊一個段落,它將是怎樣的關鍵。 –

+0

我不認爲Libgdx支持這一點。 – Tenfour04

回答

0

而不是使用font.draw方法,使用下面的一個,而不是...

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

alignmentWidth是你希望你的文字佔用的最大寬度。除此之外,它會包裝。如果你不想包裝,將其設置爲一個愚蠢的高。

「對齊」是關鍵的事情,需要一個HAlignment枚舉,可以是LEFTRIGHTCENTER

batchstrxy參數是一樣的你已經做。

+0

我嘗試過這種方法,並沒有把它拿起來。我認爲這種方法已經過時了。 –

+0

哦!對不起,我必須檢查一箇舊版本。我會稍微查看一下,找到相應的當前值。 –

1

您可以改爲使用下面的setText()方法,並將targetWidth設置爲屏幕寬度Aligh.center並將其設置爲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(); 
}