0

I have got an issue with

e.Graphics.DrawString(TextToPrint, Font, Brush, New RectangleF(StartPositionX, StartPositionY, Width, Height))

Let's say I want to print "Hello World" in Arial-20pt at 25mm on the x-axis from the left edge. In addition, I use a version with Arial-50pt.

For that I set

e.Graphics.PageUnit = GraphicsUnit.Millimeter

and

PrintDocument.OriginAtMargins = False

I print a PDF via "PDFCreator" and use the measuring tool of Acrobat Reader.

The position on the y-axis is as desired. Check!

The "H" starts at about 26.6mm (Arial-20pt) / 29.3mm (Arial-50pt).

So I also print a rectangle at the same starting points with

e.Graphics.FillRectangle

and fill it green.

This rectangle starts at 25mm!!

So I assume that there is a sort of margin around the text. On the y-axis it is possible to find the lowest point of the "H" with the help of "CellAscent".

Is there a value/function for the x-axis?

Here is my code:

e.Graphics.PageUnit = GraphicsUnit.Millimeter
PrintDocument.OriginAtMargins = False

TextToPrint = "Hello World"
Font = New Font("Arial", 20)
Brush = Brushes.Black
StartPositionX = 25
StartPositionY = 30
Width = 50
Height = 60

I want to use the exact position of the first left-bottom pixel of the "H" as my starting point. For the y-axis this works:

CellAscent = Font.Size * CSng(Font.FontFamily.GetCellAscent(Font.Style)/ Font.FontFamily.GetEmHeight(Font.Style))

StartPositionY = StartPositionY - CellAscent

After this adjustments I use

e.Graphics.DrawString(TextToPrint, Font, Brush, New RectangleF(StartPositionX, StartPositionY, .Width, .Height))

Example

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • You could try the [`Graphics.MeasureCharacterRanges` method](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.measurecharacterranges?view=netframework-4.7.2) and [`GetBounds`](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.region.getbounds?view=netframework-4.7.2) on the results. Not sure if that will give you the tight bounding box you are looking for, though. – Nico Schertler Oct 10 '18 at 09:29

1 Answers1

0

Solved

C# Font character rendering (GDI Bug)

"To avoid these problems, do the following:

Always pass MeasureString and DrawString a StringFormat object based on the typographic StringFormat (GenericTypographic) . -and- Set TextRenderingHint graphics to TextRenderingHintAntiAlias .

These measures disable the extra 1/6 em added at the run ends, avoid the problems of grid fitting by using anti-aliasing and sub-pixel glyph positioning, and result in perfectly scalable text" (from: http://support.microsoft.com/kb/307208)

DrawString(myText, myFont, myBrush, myPoint, StringFormat.GenericTypographic)