private void Button1_Click (object sender, EventArgs e)
{
Get text
string text = This.txtName.Text;
Get Bitmap (incoming Rectangle.empty automatically calculates the wide height)
Bitmap bmp = Texttobitmap (text, This.txtName.Font, Rectangle.empty, This.txtName.ForeColor, This.txtName.BackColor);
Display with PictureBox
This.pictureBox1.Image = BMP;
Save to Desktop Save.jpg
String directory = System.Environment.GetFolderPath (System.Environment.SpecialFolder.DesktopDirectory);
Bmp. Save (Directory + "\\save.jpg", imageformat.jpeg);
}
Define a method
<summary>
Convert Text to bitmap
</summary>
<param name= "Text" ></param>
<param name= "Font" ></param>
<param name= "rect" > Rectangle for Output, text is displayed inside this rectangle, automatically calculated when empty (automatic </param>
<param name= "fontcolor" > Font color </param>
<param name= "BackColor" > Background color </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);
To calculate the size of the area needed to draw the text (calculate the length based on the width), recreate the rectangular area drawing
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);
Using the ClearType font feature
G.textrenderinghint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
G.fillrectangle (New SolidBrush (BackColor), rect);
g.DrawString (text, font, brushes.black, rect, format);
return BMP;
}
Enter text in C # to create a picture of the input text