c# - 绘制文本到图像更改错误
问题描述
我想创建在图像上绘制文本的程序。为此,我使用了这种方法:
private static Image DrawText(String text, Font font, Color textColor, Color backColor)
{
//first, create a dummy bitmap just to get a graphics object
Image img = new Bitmap(1, 1);
Graphics drawing = Graphics.FromImage(img);
//measure the string to see how big the image needs to be
SizeF textSize = drawing.MeasureString(text, font);
//free up the dummy image and old graphics object
img.Dispose();
drawing.Dispose();
//create a new image of the right size
img = new Bitmap((int)textSize.Width, (int)textSize.Height);
drawing = Graphics.FromImage(img);
//paint the background
drawing.Clear(backColor);
//create a brush for the text
Brush textBrush = new SolidBrush(textColor);
drawing.DrawString(text, font, textBrush, 0, 0);
drawing.Save();
textBrush.Dispose();
drawing.Dispose();
return img;
}
我使用这个库来绘制表格并且代码看起来像上面的这个方法
var table = new ConsoleTable("one", "two", "three")
.AddRow("random text';", "random text", "random text")
.Configure(o => o.NumberAlignment = Alignment.Left)
.ToString();
DrawText(table, new Font("Verdana", 20), Color.Black, Color.White);
行确实发生了变化,它看起来不像上面的表格。我认为方法DrawText
改变了一些东西,但我不知道它到底是什么?所以我需要帮助。对不起,我的英语不好
解决方案
如果您不需要Verdana(它不是等宽字体),您应该能够通过稍微改变您的调用来解决这个问题DrawText
:
DrawText(table, new Font(FontFamily.GenericMonospace, 20), Color.Black, Color.White);
我实际上并不熟悉使用字体,所以使用FontFamily.GenericMonospace
是我最好的猜测。不过,您应该可以使用其他人。维基百科有一个他们的列表。