【C#】把TextBox的文字转成图片 您所在的位置:网站首页 头像字体图片文字雷 【C#】把TextBox的文字转成图片

【C#】把TextBox的文字转成图片

2024-07-14 22:23| 来源: 网络整理| 查看: 265

通过系统Graphics绘图把文字绘制到位图上,然后显示或保存起来,这里用定义该函数

/// /// 把文字转换才Bitmap /// /// /// /// 用于输出的矩形,文字在这个矩形内显示,为空时自动计算 /// 字体颜色 /// 背景颜色 /// 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);

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有