Is there a simple way to calculate a bounding box for a string?

I’m using SpriteBatch.DrawString(...) to render some text, and I’d like to first draw a background underneath it.

Is there a way to calculate the bounding box of a to-be-rendered text with a specific font?

Try SpriteFont.MeasureString on you font.

1 Like

So something like

Vector2 size = myfont.MesureString("my text");
Rectangle area = new Rectangle((int)pos.X, (int)pos.Y, (int)size.X, (int)size.Y);
spriteBatch.Draw(mybackground, area, Color.White);
spriteBatch.DrawString(myfont, "my text", pos, Color.White);

Also you would be better to use Convert.ToInt32 than (int) as (int)will remove any decimal value.

You mean Convert.ToInt32 will round and casting to int will just truncate the fractional part, right? Because that sentence is a bit confusing.

Yea that’s what I mean, Must have not had my morning coffee when I wrote that.

MeasureString is very costly, so you should cache this value if the string is constant between frames.
If you use a string to display the damages over the target for ex like in Diablo3, it is definitely too costly each frame as many string should be displayed. Caching is the future :slight_smile:

1 Like