yegorski
yegorski

Reputation: 395

Possible to cut an image based on the shape of another image?

In Windows Presentation Foundation, I can't seem to find a way of how to cut an image based on the shape of another image.

E.g. I'd like to display someone's photo in the shape of a heart.

There are answers like this one which crop an image into a rectangle or like this one which draw a radius to clip the image into a circle.

But is cropping really the only way?

Can WPF overlay the image on top of a shape and have the image be cut based on the shape dimensions?

The code that I have so far does the inverse of what I'm trying to do. What I have so far uses an overlay layer as a mask to cover the image:

<Image 
    Name="HeartOverlay"
    VerticalAlignment="Stretch"
    HorizontalAlignment="Stretch"
    Panel.ZIndex="2"
/>
<Canvas 
    Name="Canvas"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch">
    <Image 
        Name="Image"
        Stretch="Uniform"
        Panel.ZIndex="1"
    />
/>
HeartOverlay.Source = new Bitmap(@"C:\heart.png");
Image.Source = new Bitmap(@"C:\image.png");

The problem here is that overlay is merged together with the image and saving/printing the image also shows the overlay.

See image below as an example. Note the white borders, which are especially evident when viewing the image in something like the Mac Preview app. I'm looking to save/print the image without the white borders.

Appreciate any pointers!

heart overlay with borders

Upvotes: 0

Views: 568

Answers (1)

Clemens
Clemens

Reputation: 128061

You could simply fill a Path with a heart-shaped Geometry with an ImageBrush:

<Path Width="100" Height="150" Stretch="Uniform"
      Data="M1,2 L0,1 A0.5,0.5 1 1 1 1,0 A0.5,0.5 1 1 1 2,1 Z">
    <Path.Fill>
        <ImageBrush ImageSource="C:\image.png"/>
    </Path.Fill>
</Path>

Upvotes: 3

Related Questions