Draw a BitmapFont rotated in libgdx

倖福魔咒の 提交于 2019-11-30 20:47:49

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();

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;
}   

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();

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!