Draw a BitmapFont rotated in libgdx

2019-02-13 15:27发布

I can't seem to figure out how to rotate a Bitmap font correctly. I think you modify the transformation matrix of the SpriteBatch. However, trying to rotate that rotates the text around some point, and I don't know how to rotate it relative to the text itself.

4条回答
Juvenile、少年°
2楼-- · 2019-02-13 15:47

You can create a glyph into a sprite. That way , you can manipulate your text as a sprite.

Example code:

Note, this will return a Sprite of a single glyph. (E.g. char 'A' is transformed into a sprite.)

/** Creates a sprite from a glyph.
 * 
 * @param ch 
 * @return Sprite
 */
public Sprite getGlyphSprite (char ch) {

    Glyph glyph = Globals.g.font.getData().getGlyph(ch);
    Sprite s = new Sprite(Globals.g.font.getRegion().getTexture(),
            glyph.srcX,glyph.srcY,glyph.width, glyph.height);

    s.flip(false, true);
    s.setOrigin(glyph.width/2, glyph.height/2);

    return s;
}   
查看更多
等我变得足够好
3楼-- · 2019-02-13 15:53

I would just add.. I suppose you have font base image inside some atlas.. so you need to add TextureRegion originals sot gliph src as it is just relative to that given Texture region so

BitmapFont font = ...
BitmapFont.Glyph glyph = font.getData().getGlyph(ch);
int srcX = glyph.srcX + font.getRegion().getRegionX();
int srcY = glyph.srcY+ font.getRegion().getRegionY();
Sprite s = new Sprite(font.getRegion().getTexture(), srcX,srcY,glyph.width, glyph.height);
查看更多
做自己的国王
4楼-- · 2019-02-13 15:55

The first answer from Lunatikul didn't worked in my 2D case. It cuts my text to only a half letter. I was successfull with the following:

batch.begin();
batch.setTransformMatrix(new Matrix4().setToRotation(0,0,1,<insert angle here>));
font.draw(batch, "Hallo Welt", 100, 100);
batch.end();
查看更多
smile是对你的礼貌
5楼-- · 2019-02-13 16:06

you can try the following code:

Matrix4 mx4Font = new Matrix4();
BitmapFont font;
SpriteBatch spriteFont;

font = new BitmapFont(Gdx.files.internal("data/font/agencyFB.fnt"), Gdx.files.internal("data/font/agencyFB.png"), true); //must be set true to be flipped
mx4Font.setToRotation(new Vector3(200, 200, 0), 180);
spriteFont.setTransformMatrix(mx4Font);
spriteFont.begin();
font.setColor(1.0f, 1.0f, 1.0f, 1.0f);
font.draw(spriteFont, "The quick brown fox jumped over the lazy dog", 100, 110);
spriteFont.end();
查看更多
登录 后发表回答