Add a Label over Picturebox

房东的猫 提交于 2019-12-06 11:51:07

问题


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?


回答1:


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



回答2:


Instead of

lblPB.Parent = PB;

do

PB.Controls.Add(lblPB);



回答3:


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



回答4:


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




回答5:


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

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