如何正确地左对齐文字和拉弦? [英] How to properly left-align text with DrawString?

查看:54
本文介绍了如何正确地左对齐文字和拉弦?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将文本绘制到屏幕外的位图。遗憾的是,文本没有正确左对齐(见下图)。文本应该触及左边距(蓝色线条),但偏离了几个像素。距离随文字大小增加。

如何摆脱此距离?

我使用的是.NET框架4.6.1。但这似乎更像是一个我不理解的一般性GDI+问题。

用于生成示例的代码:

using System.Drawing;
using System.Drawing.Imaging;

namespace LeftAlignment
{
    class Program
    {
        static void Main(string[] args)
        {
            const int LeftMargin = 10;

            // create off-screen bitmap
            using (Bitmap bitmap = new Bitmap(300, 100))
            {
                // create graphics context
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    // clear bitmap
                    graphics.FillRectangle(Brushes.White, 0, 0, bitmap.Width, bitmap.Height);

                    // draw border and left margin
                    graphics.DrawRectangle(Pens.Gray, new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1));
                    graphics.DrawLine(Pens.Blue, LeftMargin, 8, LeftMargin, 92);

                    // draw string at 24 pt
                    Font font = new Font("Arial", 24);
                    graphics.DrawString("Cool water", font, Brushes.Black, LeftMargin, 8);

                    // draw string at 36 pt
                    font = new Font("Arial", 36);
                    graphics.DrawString("Cool water", font, Brushes.Black, LeftMargin, 44);
                }

                // save result as PNG
                bitmap.Save("alignment.png", ImageFormat.Png);
            }
        }
    }
}

gdi

据说微软在推荐答案+中添加了填充以使其更容易实现控件。旧的GDI没有这个问题。

当Microsoft意识到这是一个错误时,他们添加了绕过GDI+的TextRenderer class,并使用了更好的GDI实现。

填充物应该是左侧的1/6 em和右侧的1/4 em。

您有两个选项:

  1. 使用TextRenderer.DrawText。但是,它是Windows Forms的一部分。因此,它在.NET标准版和.NET Core中都不可用。

  2. 使用Graphics.DrawString和魔术选项StringFormat.GenericTypographic。它神奇地去除了填充物。

另见:

这篇关于如何正确地左对齐文字和拉弦?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆