我正在从指定的文本生成图像,但我面临一个问题:我无法删除生成的图像内绘制文本的顶部和底部填充。
我尝试在使用时更改字符串格式Graphics.DrawString()
,但我只设法删除了左右填充。
private void button1_Click(object sender, EventArgs e)
{
Font font = new Font("Arial", 52, FontStyle.Regular);
Image i = GetTextAsImage(textBox1.Text,400, font, Color.Black, Color.LightGray);
i.Save("myImage.jpeg", ImageFormat.Jpeg);
}
private Image GetTextAsImage(String text, int widthInPixel, Font textFont, 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, textFont);
//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, textFont.Height);
drawing = Graphics.FromImage(img);
drawing.SmoothingMode = SmoothingMode.AntiAlias;
drawing.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
//paint the background
drawing.Clear(backColor);
//create a brush for the text
Brush textBrush = new SolidBrush(textColor);
drawing.DrawString(text, textFont, textBrush, 0, 0,StringFormat.GenericTypographic);
drawing.Save();
textBrush.Dispose();
drawing.Dispose();
return img;
}
这是我得到的输出:
这是预期的输出: