DrawString / MeasureString Offset Problem Solved !

30 ביולי 2006

no comments

When you are trying to use DrawString and MeasureString for example to print something it seems that there is a little offset to the right and the left of the text, using MeasureString doesn’t seems to do its job.

This is how it will look:

And this is how you want it to look:

In order to solve the measuring problem all you have to do is use StringFormat with GenericTypographic and send it both to the MeasureString & to the DrawString as additional parameter.

Microsoft’s KB-307208 explains in more detail what is going on behind the gdi plus DrawString & MeasureString methods.

— Using the above method in a print preview example —

PrintPreviewDialog ppd = new PrintPreviewDialog();
System.Drawing.Printing.PrintDocument pd = new PrintDocument();
pd.PrintPage +=delegate(object printSender, PrintPageEventArgs printEventArg)
    string str = "Some String";
    Font font = new Font("Arial", 12);
    PointF location = new PointF(10, 10);
    PointF origin = new PointF(0, 0);

    StringFormat sFormat = new StringFormat(StringFormat.GenericTypographic);

    SizeF textArea = printEventArg.Graphics.MeasureString(str, font, origin, sFormat);
    printEventArg.Graphics.FillRectangle(System.Drawing.Brushes.Red, new RectangleF(location, textArea));
    printEventArg.Graphics.DrawString(str, font, System.Drawing.Brushes.Black, location,sFormat);

ppd.Document = pd;
ppd.PrintPreviewControl.Zoom = 4.0;
ppd.ClientSize = new Size(600, 300);

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>