C # String.Format and SpriteBatch.DrawString spacing issues

I have lines 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 lines should be justified with a 10-space buffer, and then the integer variables should be printed with a right-hand value with a 10 space buffer.

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

The left aligned side prints correctly, but the right aligned side is centered on a specific point, for example if kills = 50 and points = 5002, 50 will be centered over 00 at 5002 ...

What's happening?


source to share

3 answers

Simply put, I suspect you are not using a monospaced font . When different characters have different widths, you cannot use spaces for alignment. (For example, your sample works when used Console.WriteLine

, since the console has a fixed-width font by default.)

You either have to use a monospaced font, or you have to draw the lines separately - draw each line to fit the corresponding area. I don't know anything about XNA, but I expect that you will have to either measure the width of the line before you draw it (for example, you can subtract it from the right edge) or specify some type of layout value that specifies "right align the edge of this line with a specific point ".



You are most likely drawing text in a proportional font. Keep in mind that characters do not have the same width , so you cannot align texts with spaces.



Since I don't have answer privileges (or some such thing as no answer for answers), but I would like to contribute, I'll post this answer.

John replied that he measures a string, it is possible on spriteFont.MeasureString(string s);

. This returns a Vector2, the X part of which is the width of the displayed text. (Y is the height, which can be useful for other things). This allows you to use a font other than a monospaced font.

Here's a usage example MeasureString


I'm not sure what the question is asking, but if you want one line of text like "Kills: 50 Points: 5002" but the width of two different spritebatch calls you can do the following (note that I typed this directly on stackoverflow, so there may be minor syntax errors):

    float killStringWidth = spriteFont.MeasureString(killString).X;
    spriteBatch.DrawString(spriteFont, killString, new Vector2(0,0), Color.White );
    spriteBatch.DrawString(spriteFont, pointString, new Vector2(killStringWidth + 10, 0), Color.White );




All Articles