Reputation: 25919
Because of lack of Graphics object in certain places in my application, I decided to use TextRenderer class. What is quite surprising though is that it adds a lot of margins to measured text. For example:
private void button1_Click(object sender, EventArgs e) {
using (var g = this.CreateGraphics()) {
Font font = new Font("Calibri", 20.0f, GraphicsUnit.Pixel);
Size size = TextRenderer.MeasureText("Ala ma kota", font);
g.DrawRectangle(Pens.Red, new Rectangle(new Point(10, 10), size));
TextRenderer.DrawText(g, "Ala ma kota", font, new Point(10, 10), Color.Black);
}
}
Gives the following result:
Why does it do so? Is there a way to force it to get the real text size? (and of course draw it in the same rectangle it returns)
Upvotes: 1
Views: 1844
Reputation: 78190
From MSDN:
For example, the default behavior of the
TextRenderer
is to add padding to the bounding rectangle of the drawn text to accommodate overhanging glyphs. If you need to draw a line of text without these extra spaces, use the versions ofDrawText
andMeasureText
that take aSize
andTextFormatFlags
parameter, as shown in the example.
You must also pass the Graphics
object for correct results, because:
This overload of
MeasureText(String, Font, Size, TextFormatFlags)
will ignore aTextFormatFlags
value ofNoPadding
orLeftAndRightPadding
. If you are specifying a padding value other than the default, you should use the overload ofMeasureText(IDeviceContext, String, Font, Size, TextFormatFlags)
that takes aIDeviceContext
object.
Size size = TextRenderer.MeasureText(g,
"Ala ma kota",
font,
new Size(int.MaxValue, int.MaxValue),
TextFormatFlags.NoPadding);
TextRenderer.DrawText(g, "Ala ma kota", font,
new Point(10, 10),
Color.Black,
TextFormatFlags.NoPadding);
g.DrawRectangle(Pens.Red, new Rectangle(new Point(10, 10), size));
Also have a look at using the Graphics
methods directly: GDI+ MeasureString() is incorrectly trimming text
Upvotes: 4