2014-10-18 67 views
1

這是怎麼發生的?libgdx - scene2d.ui標籤高度

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()根本改變。這是甚麼...?

回答

2

似乎tBounds1和tBounds2指向同一個對象。

如果您嘗試進行檢查,它正在發生的是areSame下面是真正

boolean areSame = tBounds1 == tBounds2; 

所以tBounds1tBounds2都指向同一個對象。

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

不是cache.getBounds:本getWrappedBounds方法是通過調用。該緩存在開始創建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指向不同的對象。

+0

是的,我去分配原始類型,但我浪費了一個小時試圖首先找到問題。好吧 – PFort 2014-10-22 02:38:07