Aff*_*ikh 4 .net c# gdi+ winforms
我正在从指定的文本生成图像,但我面临一个问题:我无法删除生成的图像内绘制文本的顶部和底部填充。
我尝试在使用时更改字符串格式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;
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
这是预期的输出:
我建议您使用稍微不同的方法,使用GraphicsPath类在 Bitmap 对象上测量和绘制文本。
\n优点是该类GraphicsPath报告将绘制其包含的对象的实际坐标以及与特定字体相关的文本大小。
\n这些度量值在结构中返回RectagleF,调用GraphicsPath.GetBounds()方法。
\n基本构造函数假定 Pen 大小为 1 像素。
只需要注意一个(小)细节:GDI+ 位图对象仅接受以整数值表示的尺寸,而所有其他度量均以浮点值表示。
\n我们需要补偿舍入,但通常只是 \xc2\xb1 1 个像素。
结果示例:
\n\n程序描述:
\nGraphicsPath对象GraphicsPath文本对象的边界矩形Y位置和笔大小定义的坐标,使用它们的负值:我们需要向后移动该度量。GraphicsPath另请参阅有关字体的这些注释:
\n使用图形路径正确绘制文本
示例代码:
\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Drawing.Imaging;\nusing System.Drawing.Text;\n\n\nstring text = "This is my Text";\nFont font = new Font("Arial", 52, FontStyle.Regular, GraphicsUnit.Point);\nfloat penSize = 1f;\n\nusing (var path = new GraphicsPath()) {\n path.AddString(text, font.FontFamily, (int)font.Style, font.Size, Point.Empty, StringFormat.GenericTypographic);\n\n RectangleF textBounds = path.GetBounds();\n\n using (var bitmap = new Bitmap((int)textBounds.Width, (int)textBounds.Height, PixelFormat.Format32bppArgb))\n using (var g = Graphics.FromImage(bitmap)) \n using (var brush = new SolidBrush(Color.LightGreen)) {\n g.SmoothingMode = SmoothingMode.AntiAlias;\n // When rendering without a GraphicsPath object\n //g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;\n g.Clear(Color.Black);\n g.TranslateTransform(-(textBounds.X + penSize), -(textBounds.Y + penSize));\n g.FillPath(brush, path);\n \n bitmap.Save("[Image Path]", ImageFormat.Png);\n // Or: return (Bitmap)bitmap.Clone();\n // Or: return bitmap; declaring the bitmap without the using statement\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n