0
votes

Is it something like formula to calculate font size by given ascent height? And the same with specific width of the text? I want to draw string on the screen with specific height and width.

2
This is hard unless you are using a monospaced font (a font where each character takes the same width). In your case you probably need to know the size of each character, these are given in the .fnt file if you are using Hiero so you might want to look into that. The thing is, if you need exact numbers it's probably going to be a trial and error algorithm where you would try a specific size, measure it using GlyphLayout and go smaller if you need too.Madmenyo
Also, you might want to supply additional detail like why you need this since there might be great solutions for laying out text and UI with Scene2D but I do not know of anything to create exact length text.Madmenyo
I don't know exactly what you want, but if you want to draw string on the screen I guess you should use the Label class, so you can call getHeight and getWidth functions.Edu

2 Answers

0
votes

You can calculate a font's size on screen using a glyphlayout and scale accordingly to fit it to your predefined width/height

0
votes

Here my code to fit given width, if text is too long, the label scale to fit given width

public class MyLabel extends Label {

private float customScale = 1; //default Scale if text's width < givenWidth
private GlyphLayout layout;
private boolean isWrap; //if wrap, ignore fit
private float defaultWidth;
protected boolean autoFit = false; //set true to auto fit when text changed

@Override
public void draw(Batch batch, float parentAlpha) {
    //draw background
    if(background != null)
        batch.draw(background, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation());
    else if(background9patch != null){
        background9patch.draw(batch, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation());
    }
    //draw text
    super.draw(batch, parentAlpha);
}

@Override
public void setText(CharSequence newText) {
    super.setText(newText);
    if(autoFit){
        float prefWidth = getPrefWidth();
        if(defaultWidth == 0 && getWidth() == 0){
            setWidth(prefWidth);
        } else {
            if (layout != null && !isWrap)
                if (getWidth() > 0) {
                    getStyle().font.getData().setScale(customScale);
                    layout.setText(getBitmapFontCache().getFont(), newText);
                    float textWidth = layout.width;
                    if (textWidth > getWidth())
                        setFontScale((getWidth() / textWidth));
                    else
                        setFontScale(customScale);
                }
        }
    }
}