开发者

How to render fixed width text onto an image with c#?

I'm attempting to convert a text file to an image using a certain font (Courier New). The problem I'm having is that the font is fixed width, but the text is not being rendered that way on the image. Here's the code I'm currently using

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);

I've been trying different values for TextRenderingHint without much luck and palying around with the StringFormat.

Here's the resulting image

How to render fixed width text onto an image with c#?

Here's the text in Notepad++ displayed with Courier New Font

How to render fixed width text onto an image with c#?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜