动态添加多个PictureBox,并在PictureBox上面写字
由于项目需求,需要动态的添加多个菜单,左右两列,有同样的背景图片,就是文字不一样,开始考虑的是使用Button,设置背景,然后再设置Button的文字即可,但是遇到一个问题,就是透明的PNG图片无法实现透明,最后只能考虑使用PictureBox了,动态添加多个PictureBox,并在PictureBox上面写字
利用的是PictureBox的Paint事件,在其重绘事件时利用Graphics绘画文字
如果只是单个的PB,可以利用pictureBox1.CreateGraphics()创建Graphics对象,完成绘画
private void button1_Click(object sender, EventArgs e)
{
int leftY=50;
for (int i = 0; i < 5; i++)
{
PictureBox pb = new PictureBox();
pb.Image = global::WindowsFormsApplication2.Properties.Resources.leftempty;
pb.Size = new System.Drawing.Size(186, 67);
pb.Location = new System.Drawing.Point(30, leftY);
pb.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
leftY += 100;
this.Controls.Add(pb);
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawString("sg.com.cn ", new Font("Arial ", 10, FontStyle.Bold), SystemBrushes.ActiveCaptionText, new PointF(20, 30));
}

浙公网安备 33010602011771号