在Picturebox上添加标签

我试图在我的图片框上写一些文字,所以我认为最简单和最好的事情是在它上面绘制标签。 这就是我做的:

PB = new PictureBox(); PB.Image = Properties.Resources.Image; PB.BackColor = Color.Transparent; PB.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; PB.Size = new System.Drawing.Size(120, 30); PB.Location = new System.Drawing.Point(100, 100); lblPB.Parent = PB; lblPB.BackColor = Color.Transparent; lblPB.Text = "Text"; Controls.AddRange(new System.Windows.Forms.Control[] { this.PB }); 

我得到没有PictureBoxes的空白页面。 我究竟做错了什么?

虽然所有这些答案都有效,但您应该考虑选择更清洁的解决方案。 您可以使用图片框的Paint事件:

 PB = new PictureBox(); PB.Paint += new PaintEventHandler((sender, e) => { e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; e.Graphics.DrawString("Text", Font, Brushes.Black, 0, 0); }); //... rest of your code 

编辑以中心绘制文本:

 PB.Paint += new PaintEventHandler((sender, e) => { e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; string text = "Text"; SizeF textSize = e.Graphics.MeasureString(text, Font); PointF locationToDraw = new PointF(); locationToDraw.X = (PB.Width / 2) - (textSize.Width / 2); locationToDraw.Y = (PB.Height / 2) - (textSize.Height / 2); e.Graphics.DrawString(text, Font, Brushes.Black, locationToDraw); }); 

代替

 lblPB.Parent = PB; 

 PB.Controls.Add(lblPB); 

您必须将控件添加到PictureBox 。 所以:

 PB.Controls.Add(lblPB): 

编辑:

我得到没有PictureBoxes的空白页面。

您没有看到图片框,因为它具有与表单相同的背景颜色。 因此,尝试设置BorderStyle和BackColor。 另一个错误是你可能没有设置标签的位置。 所以:

 PB.BorderStyle = BorderStyle.FixedSingle; PB.BackColor = Color.White; lblPB.Location = new Point(0,0); 

我试过这个。 (没有使用图片框)

  1. 首先使用“面板”控件
  2. 设置面板的BackgroundImage&BackgroundImageLayout(Stretch)
  3. 添加标签内部面板

就这样

还有另一种方法可以做到这一点。 这很简单,但可能不是最好的。 (我是初学者,所以我喜欢简单的事情)

如果我理解你的问题,你想把标签放在图片框的顶部/上面。 以下代码行将执行此操作。

 myLabelsName.BringToFront(); 

现在,你的问题已经回答了,但也许这可以帮助其他人。