title: WPF: How to avoid an image get out of Canvas's borders?
body: <p>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:</p>
  
  <pre><code> &lt;Canvas Name="VisorCanvas"  Height="514"  Width="720"&gt;
     &lt;Canvas.Background&gt;
     &lt;ImageBrush /&gt;
     &lt;/Canvas.Background&gt;
     &lt;Image Name="foreground"  /&gt;
  &lt;/Canvas&gt;
  </code></pre>
  
  <p>I insert images dynamically in code behind (C#).</p>
  
  <p>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:</p>
  
  <ul>
  <li>In any case the square's image will be resized.</li>
  <li>if it's smaller than canvas's dimensions, I just show it.</li>
  <li>if it's bigger in whatever dimension (width or height), I need either to crop it or set transparent a part of image. Doing so I achieve a TV mode or something like this, since the figure will always seem "inside" the canvas (although a part is cropped)</li>
  </ul>
  
  <p>How may I do that? I've tried:</p>
  
  <ul>
  <li>To crop the image by using CroppedBitmap but it's not accurate.</li>
  <li>To use transparency through an additional opacityMask image, but I'd need to create a mask bitmap (with transparency) from the original one and I don't know how to do that.</li>
  <li>To create a "photo" by using RenderTargetBitmap and replacing the image by the result of this method, but I couldn't.</li>
  </ul>
  
  <p>I'd be grateful If someone could shed light on it.</p>