Manel
Manel

Reputation: 151

WPF: How to avoid an image get out of Canvas's borders?

I have a canvas as an image viewer. Its background is used to place an image and I'd like to put another image on top of it. So, the scenario is like this:

 <Canvas Name="VisorCanvas"  Height="514"  Width="720">
   <Canvas.Background>
   <ImageBrush />
   </Canvas.Background>
   <Image Name="foreground"  />
</Canvas>

I insert images dynamically in code behind (C#).

The problem is that if the image is too big, then the image goes beyond the Canvas's borders. For instance: I have an irrelevant background image and I want to show a square inside the Canvas panel (on top of its background) through the following way:

How may I do that? I've tried:

I'd be grateful If someone could shed light on it.

Upvotes: 15

Views: 13650

Answers (1)

Ian Griffiths
Ian Griffiths

Reputation: 14537

Set ClipToBounds="True" in your Canvas element, and that will stop the image going beyond the canvas's borders.

You might also want to consider not using an Image element. You could use a Rectangle with the Fill set to an ImageBrush because you can then use the Viewbox and Viewport properties to select which part of the source image you want, and the size of the output you want. (Set ViewportUnits to Absolute to take precise control over the dimensions of the painted area.)

Upvotes: 37

Related Questions