我正在将文本绘制到屏幕外位图。不幸的是,文本没有正确左对齐(见下图)。文本应该触及左边距(蓝线),但偏离几个像素。距离随着文本大小而增长。
我怎样才能摆脱这个距离?
我正在使用 .NET Framework 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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
据说微软在 GDI+ 中添加了填充,以便更容易地实现控件。旧的 GDI 没有这个问题。
当微软意识到这是一个错误时,他们添加了绕过 GDI+ 并使用更好的 GDI 实现的TextRenderer 类。
填充应该是左侧的 1/6 em 和右侧的 1/4 em。
您有两个选择:
使用TextRenderer.DrawText。但是,它是Windows Forms的一部分。所以它在 .NET Standard 和 .NET Core 中都不可用。
将Graphics.DrawString与魔法选项StringFormat.GenericTypographic 一起使用。它神奇地删除了填充。
另见: