如何使用c#将固定宽度的文本渲染到图像上?

时间:2011-06-02 13:23:34

标签: c# drawstring

我正在尝试使用某种字体(Courier New)将文本文件转换为图像。我遇到的问题是字体是固定宽度的,但文本没有在图像上以那种方式呈现。这是我正在使用的代码

var fontName = textToImageSection.GetString("FontName", "Courier New");
var fontSize = textToImageSection.GetInt("FontSize", 12);
textFont = new Font(fontName, fontSize);

var sf = new StringFormat(StringFormatFlags.MeasureTrailingSpaces);
sf.Trimming = StringTrimming.Character;
var text = File.ReadAllText(textFile.Path);
var image = new Bitmap(1, 1);
var textSize = new Size();
using (var g = Graphics.FromImage(image))
    textSize = g.MeasureString(text, textFont, int.MaxValue, sf).ToSize();
image = new Bitmap(image, textSize);
using (var g = Graphics.FromImage(image))
{
    g.Clear(Color.White);
    //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
    g.DrawString(text, textFont, Brushes.Black, borderLeft, borderTop, sf);
}

image.SaveAsTiff(path);

我一直在为TextRenderingHint尝试不同的价值而没有太多运气,并且使用StringFormat进行游戏。

这是结果图像

enter image description here

这是使用Courier New Font显示的Notepad ++中的文本

enter image description here

0 个答案:

没有答案