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 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);
}
}
}
}
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 usingGlyphLayout
and go smaller if you need too. – Madmenyo