In C#, Graphics.MeasureString & TextRenderer.MeasureTex, Which do we should use?
In a project I have experenced, there are many values as below:
.
.
.
SCCCCCCCCCCCCCCCCCCCCC
SSCCCCCCCCCCCCCCCCCCCC
SSSCCCCCCCCCCCCCCCCCCC
SSSSCCCCCCCCCCCCCCCCCC
SSSSSCCCCCCCCCCCCCCCCC
SSSSSSCCCCCCCCCCCCCCCC
.
.
.
S: Space
C: Character
The summary for spaces and characters in the same line is the same between every two lines.
I need evaluate the start position of characters according to the lenth of spaces, in order to all lines align in right. Then paint them on the panel.
Firstly, we evaluate the length of spaces in this way:
private float GetSpaceWidth(int spaceNum, Font font) {
string temp = new string(' ', spaceNum);
Size proposedSize = new Size(int.MaxValue, int.MaxValue);
Size s = TextRenderer.MeasureText(temp, font, proposedSize, TextFormatFlags.NoPrefix);
return s.Width;
}
Unluckily, I can not align them in right exactly. There allways exists some small difference.
After some analyze, I see that the TextRenderer.MeasureText just return Size struct. In Size struct, the type for both x and y is int. This is not exactly enough for paint align in right. Graphics.MeasureString return SizeF struct. In SizeF struct, the type for x and y is float.
So I have to update code as below:
private float GetSpaceWidth(PaintEventArgs e, int spaceNum, Font font) {
Graphics g = e.Graphics;
string temp = new string(' ', spaceNum);
StringFormat format = new StringFormat(StringFormat.GenericDefault);
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
SizeF size = g.MeasureString(temp, font, int.MaxValue, format);
return size.Width;
}
As excepted, all lines align in right this time.
Conclution: If we can get the Graphics object(OnPaint mehtod), we should use its interface
MeasureString, because it is more exact than TextRenderer.MeasureText. When no other option, use TextRenderer.MeasureText instead.
No comments:
Post a Comment