我想取一个字符串和一个指定的字体,并创建一个在框中包含该文本的图形图像,在该图像中,框会根据文本调整大小。
我得到了下面的代码,但它在做任何其他事情之前调整了盒子的大小。
是否有方法调整图像大小以适应文本(我可能需要添加几个像素的小边框)。
另外,如果我想让弦居中的话,我也不确定为什么我需要传递x,y坐标。
renderImage("Hello World", "Arial", 12, "test12.png");
renderImage("Hello", "Arial", 16, "test16.png");
renderImage("Peace Out", "Arial", 24, "test24.png");
static void renderImage(string text, string fontName, string filename, int fontsize)
{
{
System.Drawing.Bitmap objBMP = null;
System.Drawing.Graphics objGraphics = null;
System.Drawing.Font objFont = null;
objBMP = new Bitmap(531, 90);
objGraphics = System.Drawing.Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Yellow);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
objFont = new Font(fontName, fontsize, FontStyle.Bold);
StringFormat objStringFormat = new StringFormat();
objStringFormat.Alignment = StringAlignment.Center;
objStringFormat.LineAlignment = StringAlignment.Center;
objGraphics.DrawString(text, objFont, Brushes.Black, 1, 1, objStringFormat);
objBMP.Save(filename, ImageFormat.Png);
}
更新:
让它根据答案工作,但有没有更有效的方法:
static void Main(string[] args)
{
renderImage("Hello World", "Arial", 12, "test12.png");
renderImage("Hello", "Arial", 16, "test16.png");
renderImage("Peace Out", "Arial", 24, "test24.png");
}
static void renderImage(string text, string fontName, int fontSize, string filename)
{
{
System.Drawing.Bitmap objBMP = null;
System.Drawing.Graphics objGraphics = null;
System.Drawing.Bitmap objBMPTemp = null;
System.Drawing.Graphics objGraphicsTemp = null;
System.Drawing.Font objFont = null;
objFont = new Font(fontName, fontSize, FontStyle.Bold);
SizeF objSizeF = new SizeF();
objBMPTemp = new Bitmap(100, 100);
objGraphicsTemp = System.Drawing.Graphics.FromImage(objBMPTemp);
objSizeF = objGraphicsTemp.MeasureString(text, objFont);
objBMP = new Bitmap((int)objSizeF.Width, (int)objSizeF.Height);
objGraphics = System.Drawing.Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Yellow);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
objGraphics.DrawString(text, objFont, Brushes.Black, 1, 1);
objBMP.Save(filename, ImageFormat.Png);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();
}
}