C# PictureBox on top of another PictureBox

前端 未结 2 1146
甜味超标
甜味超标 2021-01-21 07:50

I want the pbGrade to be on top of pbItemtype (pb = picture box)

 pbItemtype.BackColor = Color.Transparent;

 // Change parent for over         


        
相关标签:
2条回答
  • 2021-01-21 08:30

    Well actually you can do that easily and in fact you already did.

    The code works but you also need to correct the Location as the nested PB will keep it previous one and thus will probably be off to the bottom right, probably leaving the visible size of the new Parent.... :

    pbItemtype.BackColor = Color.Transparent;
    
    // Change parent for overlay PictureBox...
    pbItemtype.Parent = pbGrade;
    // Move it to the top left of the parent:
    pbItemtype.Location = Point.Empty;  // or some other position..
    

    Transparency works well when nesting controls. It doesn't work when overlapping them, though !

    (Of course the code we see will not exchange the images!)

    0 讨论(0)
  • 2021-01-21 08:33

    Best approach is to construct the image with overlays off-line in a Bitmap object, then assign that constructed image to the PictureBox for display.

    For example like this:

    int width = 100;
    int height = 100;
    Image image = new Bitmap(width, height);
    
    using (var graphics = Graphics.FromImage(image))
    {
        graphics.DrawImage(MyApplication.Properties.Resources.ImageItemX, new Rectangle(0, 0, width, height));
        graphics.DrawImage(MyApplication.Properties.Resources.ImageGradeZ, new Rectangle(0, 0, width, height));
    }
    
    myPictureBox.SizeMode = PictureBoxSizeMode.Zoom;
    myPictureBox.Image = image;
    

    This assumes that ImageItemX and ImageGradeZ are images with a transparent background (for example pngs) imported as project resources under these names.


    For example given these resources

    the code will produce this:

    0 讨论(0)
提交回复
热议问题