Search code examples
c#formslabelpicturebox

Add a Label over Picturebox


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?


Solution

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