Add a Label over Picturebox

扶醉桌前 提交于 2019-12-04 17:54:21

While all these answers work, you should consider opting for a cleaner solution. You can instead use the picturebox's Paint event:

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

Edit To draw the text centered:

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);
});

Instead of

lblPB.Parent = PB;

do

PB.Controls.Add(lblPB);

You have to add the control to the PictureBox. So:

PB.Controls.Add(lblPB):

EDIT:

I get blank page with no PictureBoxes.

You didn't see the picturebox because it has the same backcolor of the Form. So try to set BorderStyle and the BackColor. Another mistake is that probably you haven't set the location of the label. So:

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

I tried this. (no use picturebox)

  1. Use "Panel" control first
  2. Set panel's BackgroundImage & BackgroundImageLayout (Stretch)
  3. Add Label Inside panel

that's all

There's another way to do it. It's very simple but probably not the best one. (I'm a beginner, so I like things simple)

If I've understood your question right, you want to put the label above/on top of the pictureBox. The following line of code will do that.

myLabelsName.BringToFront();

Now, your question were already answered, but maybe this can help somebody else.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!