简体   繁体   中英

Perfectly align to right drawn text in C#

When I draw text with right alignment the strings are not well aligned (I speak about horizontal alignment, I made strings overlap to compare easier):

在此处输入图片说明

It seems that there is some kind of invisible space around letters, space that varies for each letter. So the alignment varies by a few pixels.

I tried several methods, like using MeasureString , with no success.

Graphics g = Graphics.FromImage(pictureBox.Image);

FontFamily fontFamily = new FontFamily("Arial");
Font font = new Font(fontFamily, 32, FontStyle.Regular, GraphicsUnit.Pixel);
SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 0));

StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Far;

g.DrawString("tree", font, solidBrush, new PointF(161, 80), stringFormat);
g.DrawString("car", font, solidBrush, new PointF(161, 100), stringFormat);
g.DrawString("l", font, solidBrush, new PointF(161, 120), stringFormat);
g.DrawString("M", font, solidBrush, new PointF(161, 140), stringFormat);

g.Dispose();

I did find a solution for WPF, one should use Canvas.SetRight(textBlock, x); then you get a perfect alignment.

I'm still curious though about how to do it for WinForms.

Since you are drawing using GDI+.Take a look at the Various TextRenderingHints provided for the same.From Microsoft's website

For text, the font height is scaled appropriately for the device resolution: A font that is drawn 20 pixels high on a 96-dpi screen is rendered 25 pixels high on a 125-dpi screen and 125 pixels high on a 600-dpi printer. However, the width of individual glyphs will scale only approximately with the height. The exact width is also dependent on hinting instructions that have been included in the font to adjust the glyph's shape (grid fitting) for legibility.

and

Grid Fitting -- the application of TrueType hints -- is the process of adjusting the position of pixels in a rendered glyph to make the glyph easily legible at screen sizes. Hinting techniques include the alignment of glyph stems on whole pixels and insurance that similar features of a glyph are affected equally. Font designers spend many hours hinting each glyph. For example, consider the letters "s", "e", "w", and "l" from the Times New Roman font, rendered at 8 points on various resolutions, using GDI's standard grid fitting.

Take a look here http://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM