libgdx - scene2d.ui标签高度

时间:2014-10-18 21:56:23

标签: libgdx scene2d

为什么会这样?

TextBounds tBounds1 = game.font.getWrappedBounds("blah\nblah\nblah", 300);
System.out.println(""+tBounds1.height); // outputs 79.0001
TextBounds tBounds2 = game.font.getWrappedBounds("blah", 300);
System.out.println(""+tBounds1.height); // outputs 20.00002

因此变量tBounds1只是通过在另一个变量上调用getWrappedBounds()而发生了变化。这怎么样......?

1 个答案:

答案 0 :(得分:2)

似乎tBounds1和tBounds2指向同一个对象。

如果您尝试检查它们,则会发生 isSame true

boolean areSame = tBounds1 == tBounds2;

所以 tBounds1 tBounds2 指向同一个对象。 getWrappedBounds 方法由以下方法调用:

public TextBounds getWrappedBounds (CharSequence str, float wrapWidth) {
    return getWrappedBounds(str, wrapWidth, cache.getBounds());
}

不是cache.getBounds。创建BitmapFont

时,会在开始时创建缓存
private final BitmapFontCache cache;

所以缓存是当前字体的属性,因此当在那里更改某些内容时,它也会传播。

getWrappedBounds 方法也调用另一种方法:

public TextBounds getWrappedBounds (CharSequence str, float wrapWidth, TextBounds textBounds) {
    // Just removed the lines here
    textBounds.width = maxWidth;
    textBounds.height = data.capHeight + (numLines - 1) * data.lineHeight;
    return **textBounds**;
}

此方法最后改变了BitmapFontCache缓存对象。

因此,如果要计算2个不同字符串的高度,可以将其分配给基本类型:

float height1 = font.getWrappedBounds("blah\nblah\nblah", 300);
float height2 = font.getWrappedBounds("blah", 300);

或者如果你需要一个完整的BitmapFont.TextBounds对象,那么:

BitmapFont.TextBounds tBounds1 = new BitmapFont.TextBounds(font.getWrappedBounds("blah\nblah\nblah", 300));
BitmapFont.TextBounds tBounds2 = new BitmapFont.TextBounds(font.getWrappedBounds("blah", 300));

这样你就可以确保tBounds1和tBounds2指向不同的对象。