且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何生成在运行时动态从文本中的图像

更新时间:2023-10-05 09:05:52

好吧,假设你想绘制在C#中的图像上的绳子,你将需要在这里使用System.Drawing命名空间:

Ok, assuming you want to draw a string on an image in C#, you are going to need to use the System.Drawing namespace here:

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

}

这code会先衡量字符串,然后创建正确大小的图像。

This code will measure the string first, and then create an image of the correct size.

如果您想要保存此函数的返回,只需调用返回的图像的保存方法。

If you want to save the return of this function, just call the Save method of the returned image.