动态添加多个PictureBox,并在PictureBox上面写字
由于项目需求,需要动态的添加多个菜单,左右两列,有同样的背景图片,就是文字不一样,开始考虑的是使用Button,设置背景,然后再设置Button的文字即可,但是遇到一个问题,就是透明的PNG图片无法实现透明,最后只能考虑使用PictureBox了,动态添加多个PictureBox,并在PictureBox上面写字
利用的是PictureBox的Paint事件,在其重绘事件时利用Graphics绘画文字
如果只是单个的PB,可以利用pictureBox1.CreateGraphics()创建Graphics对象,完成绘画
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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)); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步