求一个打印字体到图片相关的代码!谢谢~
根据不同 ttf 字体,把字符串打印在一张刚好合适的图片上。现在的一个问题就是求这张图片的宽度要多长。
如果字符串和字体是固定倒是好办,问题就是要可变的,能动态计算打印字符需要的总宽度
怎么计算所需要的总宽度,而且是刚刚好的??????
--------------------编程问答-------------------- --------------------编程问答--------------------
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile(@"C:\微软雅黑.ttf");
FontFamily fontFamily = pfc.Families[0];
Boolean IsStyleAvailable = fontFamily.IsStyleAvailable(FontStyle.Regular);
Font font = new Font(fontFamily, fontSize, this.GetSafeFontStyle(fontInfoMode, FontStyle.Regular), GraphicsUnit.Pixel);
int imgWidth=?;//怎么计算所需要的总宽度,而且是刚刚好的
int imgHeight=?;
Image bitmap = new Bitmap(imgWidth, imgHeight, PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.DrawString("Hello,我是中国人。", font, myBrush, new PointF(nextPoint_x, 0), StringFormat.GenericTypographic);
private void MeasureStringWidth(PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
// Set maximum width of string.
int stringWidth = 200;
// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont, stringWidth);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
代码来自:
http://msdn.microsoft.com/en-us/library/9bt8ty58.aspx --------------------编程问答--------------------
string str = "这是一段测试字符串";--------------------编程问答-------------------- 测试大小后,漏了释放bmp。
Font font = new Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
//测试大小
Bitmap bmp = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(bmp);
SizeF size = g.MeasureString(str, font);
g.Dispose();
//根据测出的大小,生成相应大小的图片
Bitmap bmpNew = new Bitmap((int)Math.Ceiling(size.Width), (int)Math.Ceiling(size.Height));
Graphics gNew = Graphics.FromImage(bmpNew);
gNew.DrawString(str, font, Brushes.Black, new PointF(0, 0));
gNew.Dispose();
bmpNew.Save("001.bmp");
大致思路是先用一个空的bmp,通过MeasureString计算字符串大小,再生成相应大小的图片
--------------------编程问答-------------------- //算字符的所占像素长度
string str = "这是一段测试字符串";
Font font = new Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
//测试大小
Bitmap bmp = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(bmp);
SizeF size = g.MeasureString(str, font);
g.Dispose();
bmp.Dispose();
//根据测出的大小,生成相应大小的图片
Bitmap bmpNew = new Bitmap((int)Math.Ceiling(size.Width), (int)Math.Ceiling(size.Height));
Graphics gNew = Graphics.FromImage(bmpNew);
gNew.DrawString(str, font, Brushes.Black, new PointF(0, 0));
gNew.Dispose();
bmpNew.Save("001.bmp");
Font arialBold = new Font("SimSun", 9.0F);
Size textSize = TextRenderer.MeasureText(name, arialBold);
补充:.NET技术 , C#