引用WINDOWS API:
class="brush:csharp;gutter:true;"> [DllImport("gdi32.dll", CharSet = CharSet.Auto)] public static extern int SetTextCharacterExtra(IntPtr hdc, int nCharExtra);//图片字符间距 [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr handle); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp);
.NET 2.0
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <param name="fontSpace"></param> private void pictureBox_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Font font = new Font("宋体", 12.0F); Brush brush = Brushes.Red; string text2 = "涂聚文"; IntPtr hdc = e.Graphics.GetHdc(); SetTextCharacterExtra(hdc, 16); // 设置字符间距 e.Graphics.ReleaseHdc(hdc); e.Graphics.DrawString(text2, font, brush, 20, 25);// //pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint); }
.NET 3.5以上:
/// <summary> /// 图片的字符间距(只对中文,数字,字母,符号有效,在中文环境下,中文日文混排无效) /// 涂聚文 /// .net3.0以上 /// </summary> /// <param name="width">图片宽度</param> /// <param name="height">图片高度</param> /// <param name="space">字间距</param> /// <param name="strtext">要显示的文字</param> /// <returns>图片</returns> Bitmap CreateImageString(int width, int height,int space ,string strtext) { Bitmap image = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(image)) { //绘制图片边框 //g.DrawRectangle(Pens.Black, 0, 0, width - 1, height - 1); Font font = new Font("宋体", 12.0F); Brush brush = Brushes.Red; //绘制设置了字符间距的输出 DrawStringExtra(g, space, x => { x.DrawString(strtext, font, brush, 0, 2); }); } return image; } /// <summary> /// /// </summary> /// <param name="g"></param> /// <param name="nCharExtra"></param> /// <param name="action"></param> void DrawStringExtra(Graphics g, int nCharExtra, Action<Graphics> action) { IntPtr hdc = g.GetHdc(); SetTextCharacterExtra(hdc, nCharExtra); try { using (Graphics g1 = Graphics.FromHdc(hdc)) { action(g1); } } finally { SetTextCharacterExtra(hdc, 0); g.ReleaseHdc(hdc); } }
调用:(可以应用于打印中)
pictureBox1.Image = CreateImageStrin(100, 30, 10, "3315000");