Replicate label with DrawString method
-
19-06-2021 - |
Question
I need to draw a string over a Infragistics toolbar, and I cannot use a label since it's background will not be actually transparent (see in image).
I've managed to overlay the text as desired using DrawString method, but the problem is that the text does not resemble a label. it's thicker, aliased and for some reason black.
What should i change im my code to replicate a label's looks using the DrawString method (same font, size, forecolor) ?
And the code:
FontFamily fontFamily = new FontFamily("Microsoft Sans Serif");
Font font = new Font(
fontFamily,
17,
FontStyle.Regular,
GraphicsUnit.Pixel);
SolidBrush solidBrush = new SolidBrush(SystemColors.ControlText);
drawParams.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
drawParams.Graphics.DrawString("String Drawn with DrawString method", font, solidBrush, textEditorLoc.X, textEditorLoc.Y + 25);
Solution
Try using TextRenderer
class:
TextRenderer.DrawString(
drawParams.Graphics,
"String Drawn with TextRenderer (GDI) method",
font,
new Point(textEditorLoc.X, textEditorLoc.Y + 25),
SystemColors.ControlText);
Also leave TextRenderingHint
as SystemDefault
and use the same font size as for label.
OTHER TIPS
The standard text size of a label is 8,25 points, or approximately 11 pixels. Your size of 17 pixels results in a text size of 13 pt.
Try using this
FontFamily fontFamily = new FontFamily("Microsoft Sans Serif");
Font font = new Font(
fontFamily,
8.25f,
FontStyle.Regular,
GraphicsUnit.Point);
SolidBrush solidBrush = new SolidBrush(SystemColors.ControlText);
e.Graphics.DrawString("String Drawn with DrawString", font, solidBrush, textEditorLoc.X, textEditorLoc.Y + 25);