I am trying to write some text over my picturebox so I thought the easiest and best thing to do is draw label over it. This is what I did:
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 });
I get blank page with no PictureBoxes. What am I doing wrong?
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)
- Use "Panel" control first
- Set panel's BackgroundImage & BackgroundImageLayout (Stretch)
- 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.
来源:https://stackoverflow.com/questions/10400943/add-a-label-over-picturebox