首页 > 解决方案 > 绘制文本到图像更改错误

问题描述

我想创建在图像上绘制文本的程序。为此,我使用了这种方法:

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改变了一些东西,但我不知道它到底是什么?所以我需要帮助。对不起,我的英语不好

标签: c#

解决方案


如果您不需要Verdana(它不是等宽字体),您应该能够通过稍微改变您的调用来解决这个问题DrawText

DrawText(table, new Font(FontFamily.GenericMonospace, 20), Color.Black, Color.White);

我实际上并不熟悉使用字体,所以使用FontFamily.GenericMonospace是我最好的猜测。不过,您应该可以使用其他人。维基百科有一个他们的列表。


推荐阅读