-
Measuring A String
I'M creating a custom userlist for a chatroom program, and I'M trying to color the usernames on the list, but for some reason when I'M going through the name to color the names with the different colors when I measure the strings it keeps getting a space in between.
Code:
Dim NameFont As New Font("Tahoma", 8, FontStyle.Bold, GraphicsUnit.Point)
'e.ItemRect is the rectangle I'M drawing in
Dim UserName as String = "#c1#J#c2#o#c3#s#c4#h#c5#i#c6#e
UserName = "#c9#" & UserName
Dim StartPos As Double = e.ItemRect.Left + 56
Dim Spl() As String = Split(UserName, "#c")
For Each Item As String In Spl
Dim TColor As Color = ColorHelper.GetColorFromNumber(ColorHelper.ExtractColorNumber(Item))
Debug.WriteLine(TColor.ToString)
Dim RT As String = ColorHelper.ExtractRealString(Item)
Dim NBrush As New SolidBrush(TColor)
e.Graphics.DrawString(RT, NameFont, NBrush, StartPos, e.ItemRect.Top + 2)
'Right here, there always seems to be a space inbetween when there shouldn't be.
StartPos += e.Graphics.MeasureString(RT, NameFont).ToPointF.X
Next
-
Re: Measuring A String
A space between what exactly?
Also, while I don't a lot of direct experience with either, I have read that MeasureString can be unreliable and that MeasureCharacterRanges can provide more accurate results.
-
Re: Measuring A String
Well let's say that UserName is "#c1#J#c2#o#c3#s#c4#h#c5#i#c6#e", and each of those "#c1#" is a color code..
The way I'M doing it now comes out like this, but there is no reason for the space.
http://www.patchwinmx.com/files/spaces.png
-
Re: Measuring A String
It may well be that MeasureString adds a buffer before and after the string. I don't know that that is the case but it would be consistent with your result.
-
Re: Measuring A String
well I have tried removing specific values each time it does that, but it that doesn't work out. Because if I use other letters it has different spacing between each of them.
-
Re: Measuring A String
-
Re: Measuring A String
MeasureString does add padding spacing before and after the string when measuring by default. There may be some flags to control that in the formatting for the MeasureString method, but I personally use the TextRenderer to draw and measure text.
As mentioned, MeasureCharacterRanges may be a better approach to what you want to do. Note, however, that if you render characters instead of the whole string you may get different results based on the font. There's 'hinting' encapsulated in the font to tell the rendering engine how to draw letters when they may be next to certain other letters.