PFort
PFort

Reputation: 485

libgdx - scene2d.ui label height

Why is this happening?

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

So the variable tBounds1 has changed simply by calling getWrappedBounds() on another variable. How is this even...?

Upvotes: 1

Views: 191

Answers (1)

dawez
dawez

Reputation: 2724

Is seems that tBounds1 and tBounds2 are pointing to the same object.

If you try to check them, it is happening that areSame below it is true

boolean areSame = tBounds1 == tBounds2;

so tBounds1 and tBounds2 are pointing to the same object. The getWrappedBounds method is called by:

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

Not the cache.getBounds. The cache is created at start when creating the BitmapFont

private final BitmapFontCache cache;

so the cache is a property of the current font and therefore when something is changed there, it is also propagated.

the getWrappedBounds method calls also the other method:

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

This method at the end is changing the BitmapFontCache cache object.

So if you want to calculate the height for 2 different strings, you can assign it to primitive types:

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

or if you need a full BitmapFont.TextBounds object, this:

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

In this way you wound ensure that tBounds1 and tBounds2 are pointing to different objects.

Upvotes: 2

Related Questions