title: WPF Image Cropping
body: <p>I have a problem with image cropping. When I try to crop image with rectangle the cropping area is set to some strange value.
  Here is xaml code:</p>
  
  <pre><code>   &lt;Grid Name="GridImage"&gt;
          &lt;Image Name="LoadedImage" SnapsToDevicePixels="True" RenderOptions.BitmapScalingMode="HighQuality"&gt;
          &lt;/Image&gt;
          &lt;Canvas  x:Name="ImageCanvas" ClipToBounds="True"&gt;
              &lt;Rectangle x:Name="SelectionRectangle" Stroke="LightBlue" Fill="#220000FF" Visibility="Collapsed" /&gt;
          &lt;/Canvas&gt;
    &lt;/Grid&gt;
  </code></pre>
  
  <p>and here how I crop image:</p>
  
  <pre><code>            var imagePosition = LoadedImage.TransformToAncestor(GridImage).Transform(new Point(0, 0));
              Rect rect1 = new Rect(Math.Max(Canvas.GetLeft(SelectionRectangle) - imagePosition.X, 0), Math.Max(Canvas.GetTop(SelectionRectangle) - imagePosition.Y, 0), SelectionRectangle.Width, SelectionRectangle.Height);
              var ratioX = LoadedImage.Source.Width / LoadedImage.ActualWidth;
              var ratioY = LoadedImage.Source.Height / LoadedImage.ActualHeight;
  
  
              Int32Rect rcFrom = new Int32Rect
              {
                  X = (int)(rect1.X * ratioX),
                  Y = (int)(rect1.Y * ratioY),
                  Width = (int)(rect1.Width * ratioX),
                  Height = (int)(rect1.Height * ratioY)
              };
              try
              {
                  BitmapSource bs = new CroppedBitmap((BitmapSource)LoadedImage.Source, rcFrom);
                  LoadedImage.Source = bs;
                  SetImageStretch(LoadedImage);
                  SetElementVisibility(Visibility.Hidden, Visibility.Visible, SelectionRectangle);
              }
  
  
      private void SetImageStretch(Image image)
      {
          if (image.Source.Width &gt; image.ActualWidth || image.Source.Height &gt; image.ActualHeight)
              image.Stretch = Stretch.Uniform;
          else image.Stretch = Stretch.None;
      }
  </code></pre>
  
  <p>Does anybody know how to fix that?   </p>
  
  <p>Here how it looks before cropping:</p>
  
  <p><a href="https://i.stack.imgur.com/P2uNQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P2uNQ.png" alt="enter image description here"></a></p>
  
  <p>How it looks after cropping:</p>
  
  <p><a href="https://i.stack.imgur.com/x20HH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x20HH.jpg" alt="enter image description here"></a></p>