How to calculate the base line of text in .NET while using System.Windows.Forms.TextRenderer?

343 views Asked by At

My goal is to draw text by specifying its baseline origin point and not the upper left origin point as is the default in .NET.

https://stackoverflow.com/a/8290654 This does not seem to work or I'm still doing something wrong.

I already tried graphics.DrawString() but with that method I also had to deal with an unwanted padding to the left of the text.

So now I'm using System.Windows.Forms.TextRenderer to draw on a bitmap. With System.Windows.Forms.TextFormatFlags.NoPadding it was easy to get rid of the left padding.

As you can see in the example [P1] is the desired baseline. [P2] is my calculated baseline according to example in the link above.

Dim ascent As Integer = font.FontFamily.GetCellAscent(FontStyle.Regular)
Dim lineSpacing As Integer = font.FontFamily.GetLineSpacing(FontStyle.Regular)
Dim baseline As Single = font.GetHeight(graphics) * ascent / lineSpacing
Dim baselinePoint As PointF = _originPointF
baselinePoint.Y += baseline

enter image description here

As you can see [P2] ends up too far on the y-axis.

My idea is, that if I can get the baseline calculation right, I just use the y-value as an offset.

As you can see in the example [P1] is at the baseline of the red text. This is actually the behavior of the Android API when drawing text and I'm trying to emulate this in .NET.

I'm using the Robot font which can be downloaded here. (I hope there is nothing weird goint on "in" the font.)

There is this space between [P1] and the top side of "Afh". If that is the external leading it seems pretty cumbersome to get at it via System.Windows.Forms.VisualStyles.VisualStyleRenderer.GetTextMetrics() and I'm getting the feeling I'm missing something.

The height of the "A" is - as far as I understand it - the GetCellAscent value.

Here are some links I found useful thus far:
How to: Obtain font metrics
Font Metrics and the Use of Negative lfHeight

0

There are 0 answers