博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用GDI+ DrawDriverString实现行距及字符间距控制
阅读量:5089 次
发布时间:2019-06-13

本文共 7127 字,大约阅读时间需要 23 分钟。

主要是要将一个标题和几段文字绘制到固定大小的图片上,如果一张放不下就生成多张。在使用DrawString是发现无法控制行距

namespace TibetTest {     public class Utils     {         //     }     public class ConvertImage     {         public bool TextToImage(string title_Text, string title_FontFamily, float title_FontEmSize, FontStyle title_FontStyle, Color title_Color, int title_MarginTop, int title_MarginBottom,             string content_Text, string content_FontFamily, float content_FontEmSize, FontStyle content_FontStyle, Color content_Color, int content_RowSpacing, int content_WordSpacing,             int page_Width, int page_Height, int page_MarginLeftRight, int page_MarginTop, Color background_Color, string SavePath)         {             //TODO:检测并修正参数             System.Drawing.Bitmap bit = new System.Drawing.Bitmap(page_Width, page_Height);             System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bit);             g.SmoothingMode = SmoothingMode.HighQuality;             g.InterpolationMode = InterpolationMode.HighQualityBicubic;             g.CompositingQuality = CompositingQuality.HighQuality;             g.Clear(background_Color);             //--写标题--本代码假定标题内容不会超出一页             Font title_font = new Font(title_FontFamily, title_FontEmSize, title_FontStyle);             Brush title_brush = new SolidBrush(title_Color);             SizeF size = g.MeasureString(title_Text, title_font, page_Width - page_MarginLeftRight * 2);             g.DrawString(title_Text, title_font, title_brush,                 new RectangleF(new PointF(page_MarginLeftRight, title_MarginTop), //标题的上边距单独指定                     new SizeF(page_Width - page_MarginLeftRight * 2, page_Height - title_MarginTop)));             //--计算内容每个字符的显示位置             Font font = new Font(content_FontFamily, content_FontEmSize, content_FontStyle);             Brush brush = new SolidBrush(content_Color);             List<PageClass> lpageClass = GetShowList(content_Text, g, font, page_Width, page_Height, content_RowSpacing, content_WordSpacing, size.Height + title_MarginTop + title_MarginBottom, page_MarginLeftRight, page_MarginTop);             foreach (PageClass pc in lpageClass)             {                 if (pc.pageindex > 1)                 {                     g.Dispose();                     bit.Dispose();                     bit = new System.Drawing.Bitmap(page_Width, page_Height);                     g = System.Drawing.Graphics.FromImage(bit);                     g.Clear(background_Color);                     g.SmoothingMode = SmoothingMode.HighQuality;                     g.InterpolationMode = InterpolationMode.HighQualityBicubic;                     g.CompositingQuality = CompositingQuality.HighQuality;                 }                 GDIMethods.DrawDriverString(g, pc.txt, font, brush, pc.pos);                 bit.RotateFlip(RotateFlipType.Rotate90FlipXY);                 bit.Save(string.Format(SavePath, pc.pageindex), System.Drawing.Imaging.ImageFormat.Bmp);

            }             return true;

        }         /// <summary>         /// 计算内容每个字符的显示位置,根据字符大小自动分行,支持空格、换行、两边自动对齐         /// </summary>         /// <param name="txt">文本内容</param>         /// <param name="g">绘图区域</param>         /// <param name="font">字体</param>         /// <param name="pagewidth">页宽</param>         /// <param name="pageheight">页高</param>         /// <param name="rowspace">行距</param>         /// <param name="wordspace">字符间距</param>         /// <param name="firstPageMaginTop">首页上边距</param>         /// <param name="marginleftright">页左右边距</param>         /// <param name="margintop">普通页上边距</param>         /// <returns></returns>         public List<PageClass> GetShowList(string txt, Graphics g, Font font, int pagewidth, int pageheight,             float rowspace, float wordspace, float firstPageMaginTop, int marginleftright, int margintop)         {             int pageindex = 1;             float left = 0, top = firstPageMaginTop + font.SizeInPoints;             ;             float lastRight = marginleftright - wordspace;             float lastRowBotton = top;             float rowheight = font.SizeInPoints + rowspace;             int colstart = 0, colend = 0;             float colspace;             string curTxt, measureStr;             SizeF size;             List<PointF> lpos = new List<PointF>();             List<PageClass> lpageClass = new List<PageClass>();             PageClass curPage = new PageClass();             System.Text.StringBuilder str = new System.Text.StringBuilder();             for (int i = 0; i < txt.Length; i++) //这个字在这行放不下,要放到下一行             {                 curTxt = txt.Substring(i, 1);                 switch (curTxt)                 {                     case " ":                         measureStr = "2";                         break;                     case "\t":                         measureStr = "2222";                         break;                     case " ":                         measureStr = "国";                         break;                     default:                         measureStr = curTxt;                         break;                 }                 size = g.MeasureString(measureStr, font, int.MaxValue, StringFormat.GenericTypographic);                 left = lastRight + wordspace;                 if ((left + size.Width) > pagewidth || curTxt == "\n")                 {                     if (curTxt != "\n")                     {                         colspace = (pagewidth - lastRight - marginleftright) / (colend - colstart);                         for (int j = colstart; j < colend; j++)//处理两边对齐                         {                             lpos[j] = new PointF(lpos[j].X + colspace * (j - colstart + 1), lpos[j].Y);                         }                     }                     colstart = colend;

                    left = marginleftright;                     top = lastRowBotton + rowheight;

                    lastRowBotton = top;                 }                 colend++;                 lastRight = left + size.Width;

                if (top > pageheight) //这行应该放到下一页了                 {                     curPage.pageindex = pageindex;                     curPage.txt = str.ToString();                     curPage.pos = lpos.ToArray();                     lpageClass.Add(curPage);

                    pageindex++;                     curPage = new PageClass();                     lpos.Clear();                     //str.Clear();                     str.Remove(0, str.Length);                     top = margintop + rowheight;                     lastRowBotton = top;                     colstart = 0;                     colend = 1;                 }

                str.Append(curTxt);                 lpos.Add(new PointF(left, top));

            }             //保存最后一页             if (lpos.Count > 0)             {                 curPage.pageindex = pageindex;                 curPage.txt = str.ToString();                 curPage.pos = lpos.ToArray();                 lpageClass.Add(curPage);             }             return lpageClass;         }     }

    public class PageClass     {         public int pageindex;         public string txt;         public PointF[] pos;     }

    public class GDIMethods     {         private GDIMethods() { }

        private enum DriverStringOptions         {             CmapLookup = 1,             Vertical = 2,             Advance = 4,             LimitSubpixel = 8,         }

        public static void DrawDriverString(Graphics graphics, string text,             Font font, Brush brush, PointF[] positions)         {             DrawDriverString(graphics, text, font, brush, positions, null);         }

        public static void DrawDriverString(Graphics graphics, string text,             Font font, Brush brush, PointF[] positions, Matrix matrix)         {             if (graphics == null)                 throw new ArgumentNullException("graphics");             if (text == null)                 throw new ArgumentNullException("text");             if (font == null)                 throw new ArgumentNullException("font");             if (brush == null)                 throw new ArgumentNullException("brush");             if (positions == null)                 throw new ArgumentNullException("positions");

            // Get hGraphics             FieldInfo field = typeof(Graphics).GetField("nativeGraphics",                 BindingFlags.Instance | BindingFlags.NonPublic);             IntPtr hGraphics = (IntPtr)field.GetValue(graphics);

            // Get hFont             field = typeof(Font).GetField("nativeFont",                 BindingFlags.Instance | BindingFlags.NonPublic);             IntPtr hFont = (IntPtr)field.GetValue(font);

            // Get hBrush             field = typeof(Brush).GetField("nativeBrush",                 BindingFlags.Instance | BindingFlags.NonPublic);             IntPtr hBrush = (IntPtr)field.GetValue(brush);

            // Get hMatrix             IntPtr hMatrix = IntPtr.Zero;             if (matrix != null)             {                 field = typeof(Matrix).GetField("nativeMatrix",                     BindingFlags.Instance | BindingFlags.NonPublic);                 hMatrix = (IntPtr)field.GetValue(matrix);             }

            int result = GdipDrawDriverString(hGraphics, text, text.Length,                 hFont, hBrush, positions, (int)DriverStringOptions.CmapLookup, hMatrix);         }

        [DllImport("Gdiplus.dll", CharSet = CharSet.Unicode)]         internal extern static int GdipMeasureDriverString(IntPtr graphics,             string text, int length, IntPtr font, PointF[] positions,             int flags, IntPtr matrix, ref RectangleF bounds);

        [DllImport("Gdiplus.dll", CharSet = CharSet.Unicode)]         internal extern static int GdipDrawDriverString(IntPtr graphics,             string text, int length, IntPtr font, IntPtr brush,             PointF[] positions, int flags, IntPtr matrix);     }

}

转载于:https://www.cnblogs.com/1175429393wljblog/p/4964455.html

你可能感兴趣的文章
Win 10 文件浏览器无法打开
查看>>
HDU 1212 Big Number(C++ 大数取模)(java 大数类运用)
查看>>
-bash: xx: command not found 在有yum源情况下处理
查看>>
[leetcode]Minimum Path Sum
查看>>
内存管理 浅析 内存管理/内存优化技巧
查看>>
hiho1079 线段树区间改动离散化
查看>>
【BZOJ 5222】[Lydsy2017省队十连测]怪题
查看>>
第二次作业
查看>>
【input】 失去焦点时 显示默认值 focus blur ★★★★★
查看>>
Java跟Javac,package与import
查看>>
day-12 python实现简单线性回归和多元线性回归算法
查看>>
Json格式的字符串转换为正常显示的日期格式
查看>>
[转]使用 Razor 进行递归操作
查看>>
[转]Android xxx is not translated in yyy, zzz 的解决方法
查看>>
docker入门
查看>>
Android系统--输入系统(十一)Reader线程_简单处理
查看>>
监督学习模型分类 生成模型vs判别模型 概率模型vs非概率模型 参数模型vs非参数模型...
查看>>
Mobiscroll脚本破解,去除Trial和注册时间限制【转】
查看>>
实验五 Java网络编程及安全
查看>>
32位与64位 兼容编程
查看>>