I want to use DrawString
to vertically align text with different size fonts. Basically I am trying to print a sell price on a report with the cents printed in a smaller font than than the dollars. This is in a report engine and I need to write to an image, not a Windows Form so I believe I have to use DrawString
rather than using TextRenderer
.
I have found various articles explaining how to draw text on the BaseLine. These seem to work OK although I am finding that the same font at different sizes can be out by a pixel. I thought I could take these and work out how to align using the ascent design info for the font but I haven't been successful :-(
Does anyone have some sample code that would help?
Update 1: Change the total to reflect that I want top align not vertically aligned. I want the top of the dollar value printed in say Arial 20 to horizontally align with the top of the cents value in Arial 14. All fonts that I have tried have had a problem.
In the following image, I am using Arial Black.
You can see with the larger fonts there is a gap between the red line and top of 1 but that disappears by the time it gets to the smaller fonts.
With Arial it starts above the line.
And I think this one was Verdana which starts with a bigger gap at the bigger fonts.
For these three I am using the following code:
float offset = myFont.SizeInPoints /
myFont.FontFamily.GetEmHeight(myFont.Style) *
(myFont.FontFamily.GetLineSpacing(myFont.Style) - myFont.FontFamily.GetCellAscent(myFont.Style));
float pixels = e.Graphics.DpiY / 72f * offset;
float baseline = pixels;// (int)(pixels + 0.5f);
PointF renderPt = new PointF(left, y - baseline);
e.Graphics.DrawString("$1", myFont, new SolidBrush(Color.Black), renderPt);
I also used this sample as a basis for some tests. I figured if the way the ascent line was drawn was accurate then I could simply adjust the initial write point. Alas, when you go to bigger font sizes or different fonts, the ascent line is drawn inaccurately and so I couldn't pursue that path.
I haven't used TextRenderer
as I couldn't work out how to get it to work since I am not using a windows form OnPaint
event and couldn't work out how to get the appropriate graphics. Been a bit pressed for time but I think that might have top be my next option.