我正在尝试在图片框上写一些文本,所以我认为最简单也是最好的方法是在其上绘制标签。这就是我所做的:
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);
还有另一种方法。这很简单,但可能不是最好的。 (我是一个初学者,所以我喜欢简单的东西)
如果我正确理解了您的问题,则希望将标签放在pictureBox的上方/上方。下面的代码行将做到这一点。
myLabelsName.BringToFront();
现在,您的问题已经得到回答,但这也许可以帮助其他人。
如何在Picturebox单击事件中从Picturebox获取标签值