Search code examples
c#imagetransparencyparent

Assigning parent to image stored in Image Array


I am storing images in an Array, which I am going to display on top of each other (using transparency) in an image box, but how do I set the parent of each image (to enable transparency)?

Is it something along the lines of

images[1].parent = images[0];

Note, the above code does not work hence the question.


Solution

  • Wrap you images in a class with the property or properties you need (Bitmap is sealed, so you can't just inherit from it):

    public class MyImageWrapper 
    {
        public MyImageWrapper Parent { get; set; }
        public Image Image { get; set; }
    
        public MyImageWrapper(Image i, MyImageWrapper parent = null)
        {
            Parent = parent;
            Image = i;
        }
    }
    

    Now you can change your array of Image to an array MyImageWrapper and you can do things like this:

    Images[1].Parent = Images[0]
    

    Of course, you need to remember to access the wrapped image before you try and assign it to a control that expects an Image, for example:

    pictureBox1.Image = Images[0].Image;
    

    And to originally load your images, you would:

    images[0] = new ImageWrapper(Image.FromFile("MyImage.png"));