Paul
Paul

Reputation: 121

How to overlay images in WPF?

I have two images which I need to overlap.

For ex- I need a solid circle on top of a solid rectangle. So, I can see the entire circle but only the corners of the rectangle. I do not want the circle to be transparent. The original circle.png does NOT have a rectangular border. Its border is along the boundaries of the circle only. Thus, ideally, the entire circle should not overlap the rectangle.

This is the code for displaying an image:

                BitmapImage src = new BitmapImage();
                src.BeginInit();
                src.UriSource = new Uri(imgpath, UriKind.Absolute);
                src.CacheOption = BitmapCacheOption.OnLoad;
                src.EndInit();
                ImageBrush ib = new ImageBrush(src);
                ib.Viewbox = new Rect(UVRectangle.X / src.PixelWidth, UVRectangle.Y / src.PixelHeight, UVRectangle.Width / src.PixelWidth, UVRectangle.Height / src.PixelHeight);
                gr.Background = ib; //gr is of type Grid

However, if I call this function twice, the second image (circle) completely covers the rectangle and thus, I end up seeing the background of the canvas instead of the corners of the rectangle.

I think I need to merge the two images and then paint them. How should I go about doing this?

Upvotes: 4

Views: 6173

Answers (2)

Claudio P
Claudio P

Reputation: 2203

You override the property Background with your second call. If you add two Images to your Grid programmatically it would work. Change:

gr.Background = ib;

To:

Image image = new Image();
image.Source = ib.ImageSource;  
gr.Children.Add(image);

Upvotes: 1

Gope
Gope

Reputation: 1778

Actually you can just an ordinary Grid within your XAML. Just place 2 images inside the grid. They will be placed over each other like this:

<Grid>
        <Image Source="/ProjectName;component/Folder/Image1.png"
                                Width="24"
                                Height="24" />
        <!-- Image above Image1 -->
        <Image Source="/ProjectName;component/Folder/Image2.png"
                                Width="24"
                                Height="24" />
    </Grid>

Upvotes: 5

Related Questions