Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# String.Format and SpriteBatch.DrawString spacing issues

I have strings formatted using the code below

String.Format("{0,-10} {1,10}", "Kills:", kills);
String.Format("{0,-10} {1,10}", "Points:", points);
String.Format("{0,-10} {1,10}", "$:", currency);

From what I understood, the first part of the strings should be left justified with a 10 space buffer and then the integer variables should be printed right justified with a 10 space buffer.

However when attempt to draw the strings using SpriteBatch.DrawString, nothing aligns properly.

The left aligned side prints properly, but the right aligned side centres on a certain point, for example if kills = 50 and points = 5002, the 50 will be centered over the 00 in the 5002...

What is going on?

like image 281
kbirk Avatar asked Dec 14 '25 16:12

kbirk


1 Answers

Quite simply, I suspect you're not using a monospaced font. When different characters have different widths, you can't use spaces to line things up. (Your sample works when using Console.WriteLine for example, as the console has a fixed width font by default.)

You'll either have to use a monospaced font, or you'll have to draw the strings separately - draw each string to fit the relevant area. I don't know anything about XNA, but I'd expect you to either have to measure the width of the string before you draw it (so you can subtract it from the right-hand edge, for example) or specify some sort of layout value which indicates "right-align this string with a particular point".

like image 129
Jon Skeet Avatar answered Dec 16 '25 06:12

Jon Skeet