主要是要将一个标题和几段文字绘制到固定大小的图片上,如果一张放不下就生成多张。在使用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); }
}