【问题标题】:Libgdx font sizeLibgdx 字体大小
【发布时间】:2017-04-07 12:38:17
【问题描述】:

通过给定的上升高度计算字体大小是否类似于公式?与特定宽度的文本相同吗?我想在屏幕上绘制具有特定高度和宽度的字符串。

【问题讨论】:

  • 这很难,除非您使用monospaced 字体(每个字符采用相同宽度的字体)。在您的情况下,您可能需要知道每个字符的大小,如果您使用的是Hiero,这些在.fnt 文件中给出,因此您可能需要调查一下。问题是,如果您需要确切的数字,它可能会是一个试错算法,您会尝试特定的尺寸,使用GlyphLayout 测量它,如果您也需要更小。
  • 另外,您可能需要提供额外的详细信息,例如为什么需要这个,因为可能有很好的解决方案来使用 Scene2D 布置文本和 UI,但我不知道如何创建精确长度的文本。
  • 我不知道你到底想要什么,但是如果你想在屏幕上绘制字符串我想你应该使用 Label 类,这样你就可以调用 getHeight 和 getWidth 函数。

标签: fonts libgdx


【解决方案1】:

这里我的代码适合给定宽度,如果文本太长,标签缩放以适合给定宽度

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

【讨论】:

    【解决方案2】:

    您可以使用glyphlayout 计算屏幕上字体的大小并相应地缩放以适应您预定义的宽度/高度

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-11
      • 2014-11-30
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 2012-04-25
      相关资源
      最近更新 更多