winform label文本转换为图片 、Picturebox+label合并转换为图片

 1  public Form1()
 2         {
 3             InitializeComponent();
 4             //label存入Picturebox
 5             pictureBox1.Controls.Add(label1);
 6             pictureBox1.Controls.Add(label2);
 7         }
 8 
 9         private void button1_Click(object sender, EventArgs e)
10         {
11             //Picturebox+label合并转换成图片
12             foreach (Label l in pictureBox1.Controls)
13             {
14 
15                 using (Brush brush = new SolidBrush(l.ForeColor))
16                 using (Graphics g = Graphics.FromImage(pictureBox1.Image))
17                 {
18                     Rectangle rect = new Rectangle(l.Left - pictureBox1.Left, l.Top - pictureBox1.Top, l.Width, l.Height);
19                     if (l.BackColor != Color.Transparent)
20                     {
21                         using (Brush bgBrush = new SolidBrush(l.BackColor))
22                         {
23                             g.FillRectangle(bgBrush, rect);
24                         }
25                     }
26                     g.DrawString(l.Text, l.Font, brush, rect, StringFormat.GenericTypographic);
27                 }
28             }
29             pictureBox1.Image.Save("d:\\abc.png", System.Drawing.Imaging.ImageFormat.Png);
30 
31             //文字转换成图片
32             //string str =label1.Text;
33             //Graphics g = Graphics.FromImage(new Bitmap(1, 1));
34             //Font font = new Font("宋体", 9);
35             //SizeF sizeF = g.MeasureString(str, font); //测量出字体的高度和宽度  
36             //Brush brush; //笔刷,颜色  
37             //brush = new SolidBrush(label1.ForeColor);
38             //PointF pf = new PointF(0, 0);
39             //Bitmap img = new Bitmap(Convert.ToInt32(sizeF.Width), Convert.ToInt32(sizeF.Height));
40             //g = Graphics.FromImage(img);
41             //g.DrawString(str, font, brush, pf);
42             ////输出图片  
43             //img.Save("d://123.jpg", System.Drawing.Imaging.ImageFormat.Gif);
44
45         }

 

posted @ 2016-12-26 14:19  云中的angel王  阅读(1167)  评论(0编辑  收藏  举报