用 C# 在图片上写一层文字,但文字总是出现偏移。怎么发现的呢,我在 HTML 中写的文字总要紧些,而 C# 图片上生成的文字间距总要大些。
解决办法public void Draw(Graphics g)
{
GraphicsPath gp = new GraphicsPath();
//往图层中添加字符串
gp.AddString(Text,
new FontFamily(FontName),
(IsBold ? (int)FontStyle.Bold : (int)FontStyle.Regular),
FontSize,
new Point(LocationX, LocationY),
StringFormat.GenericTypographic); // 使用 GenericTypographic,而非 GenericDefault,以避免文字偏移
g.FillPath(new SolidBrush(ForeColor), gp);
g.DrawPath(new Pen(Color.White, 1), gp); // 描边
}
关键的一句是在 AddString 中最后一个参数是 StringFormat.GenericTypographic。
本文用的 GraphicsPath 来写字,优点比较多。当然,也可以直接调用 Graphics 的 DrawString,请参见 画图与图像处理-写字与画线。