• 0

[C# Tip] Converting ContentAlignment to StringAlignment


Question

Recently, while writing my own custom button, I needed to convert the TextAlign property to something I can use in DrawString. This initially proofed not as simple as I thought because TextAlign uses the ContentAlignment type, and DrawString uses the far simple StringAlignment.

I spent a good half a day scouring the internet, and I really couldn't believe what I found. It seems that the ONLY way that anyone had found how to do this relatively simple task, was with a switch statement! Laboriously checking which TextAlignment was being used, and manually setting the .LineAlignment and .Alignment properties of the StringFormat object before sending it to graphics.DrawString.

Experience has taught me that, in C#, there are usually many solutions that will work, but most of them are complete and utter garbage, and it struck me that there's no way that a long assed switch statement was the right solution. So I had a look at the actual values of the enums for ContentAlignment and StringAlignment, and realised that really, the solution is actually very simple; you just need to use a little math.

Convert ContentAlignment to StringAlignment

StringFormat cFormat;
Int32 lNum =  (Int32)Math.Log((Double)this.TextAlign, 2);
cFormat.LineAlignment = (StringAlignment)(lNum / 4);
cFormat.Alignment = (StringAlignment)(lNum % 4);

...you then just use the cFormat object in your DrawString.

That's it! Simple really, isn't it?

  • Like 1
Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

Very cool. Thanks for sharing. I've always resorted to using the Switch statement and I agree, it's not very elegant. This will save me all of that hassle in the future. +1 internets for you, sir!

Link to comment
Share on other sites

  • 0

DrawString is part of the Graphics namespace and is used when drawing strings on to any graphics object. In my particular case, an owner drawn WinForms button. It's not really anything to do directly with XNA at all, it's GDI territory.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.