通过给定的上升高度计算字体大小是否类似于公式?和文本的特定宽度相同吗?我想在屏幕上绘制具有特定高度和宽度的字符串。
这里我的代码适合给定的宽度,如果文本太长,标签缩放以适合给定的宽度
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);
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句