【亲测可行,图片宽度高度自适应】c# Graphics MeasureString精确测量字体宽度
public static Bitmap GetImage(string number, float fontSize, int color_red = 40, int color_green = 124, int color_blue = 254) { int count = number.Length; //需要配置的字段 //Font f = new Font("Microsoft Sans Serif", fontSize);//, System.Drawing.FontStyle.Bold);//设置字体样式,大小 Font f = new Font("思源宋体", fontSize);//, System.Drawing.FontStyle.Bold);//设置字体样式,大小 #region 测量字体宽度 Bitmap image_size = new Bitmap(20 * count, f.Height);//初始化大小 Graphics size_g = Graphics.FromImage(image_size); SizeF sizeF = size_g.MeasureString(number, f); #endregion Bitmap image = new Bitmap((int)sizeF.Width, (int)sizeF.Height);//初始化大小 Random random = new Random(); try { Graphics g = Graphics.FromImage(image); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置图片质量 g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;//.Drawing.Text.TextRenderingHint.SingleBitPerPixel; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; Brush b = new SolidBrush(Color.FromArgb(color_red, color_green, color_blue)); RectangleF rectangleF = new RectangleF(0, 0, sizeF.Width, sizeF.Height); //设置位置 g.DrawString(number, f, b, rectangleF); return image; } finally { } }
本文来自博客园,作者:沉迷编程的程序员,转载请注明原文链接:https://www.cnblogs.com/codeDevotee/p/11874959.html
欢迎各位找我代写程序,python、c#、web等都可以,加我请注明博客园微信:A15919195482