通過系統Graphics繪圖把文字繪制到位圖上,然後顯示或保存起來,這裡用定義該函數
/// <summary> /// 把文字轉換才Bitmap /// </summary> /// <param name="text"></param> /// <param name="font"></param> /// <param name="rect">用於輸出的矩形,文字在這個矩形內顯示,為空時自動計算</param> /// <param name="fontcolor">字體顏色</param> /// <param name="backColor">背景顏色</param> /// <returns></returns> private Bitmap TextToBitmap(string text, Font font, Rectangle rect, Color fontcolor, Color backColor) { Graphics g; Bitmap bmp; StringFormat format = new StringFormat(StringFormatFlags.NoClip); if (rect == Rectangle.Empty) { bmp = new Bitmap(1, 1); g = Graphics.FromImage(bmp); //計算繪制文字所需的區域大小(根據寬度計算長度),重新創建矩形區域繪圖 SizeF sizef = g.MeasureString(text, font, PointF.Empty, format); int width = (int)(sizef.Width + 1); int height = (int)(sizef.Height + 1); rect = new Rectangle(0, 0, width, height); bmp.Dispose(); bmp = new Bitmap(width, height); } else { bmp = new Bitmap(rect.Width, rect.Height); } g = Graphics.FromImage(bmp); //使用ClearType字體功能 g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; g.FillRectangle(new SolidBrush(backColor), rect); g.DrawString(text, font, Brushes.Black, rect, format); return bmp; }
把textbox1文本的內容輸出為jpg圖片
//獲取文本 string text = this.textbox1.Text; //得到Bitmap(傳入Rectangle.Empty自動計算寬高) Bitmap bmp = TextToBitmap(text, this.textbox1.Font, Rectangle.Empty, this.textbox1.ForeColor, this.textbox1.BackColor); //用PictureBox顯示 this.pbTextView.Image = bmp; //保存到桌面save.jpg string directory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory); bmp.Save(directory + "\\save.jpg", ImageFormat.Jpeg);