2016-08-19 293 views
1

我有一個圖像裁剪問題。當我嘗試使用矩形裁剪圖像時,裁剪區域被設置爲一些奇怪的值。 這裏是XAML代碼:WPF圖像裁剪

<Grid Name="GridImage"> 
     <Image Name="LoadedImage" SnapsToDevicePixels="True" RenderOptions.BitmapScalingMode="HighQuality"> 
     </Image> 
     <Canvas x:Name="ImageCanvas" ClipToBounds="True"> 
      <Rectangle x:Name="SelectionRectangle" Stroke="LightBlue" Fill="#220000FF" Visibility="Collapsed" /> 
     </Canvas> 
    </Grid> 

這裏我剪切圖像如何:

  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 > image.ActualWidth || image.Source.Height > image.ActualHeight) 
      image.Stretch = Stretch.Uniform; 
     else image.Stretch = Stretch.None; 
    } 

有誰知道如何解決這個問題?
Here how it looks before cropping

How it looks after cropping

+0

沒有一個很好的[mcve]可以可靠地再現你的問題,所以你不可能知道你需要什麼答案。最有可能的是,你根本不應該創建一個新的位圖,而是應該依靠「Image」元素的變換選項來簡單地約束原始位圖在屏幕上的顯示方式。請提供一個好的MCVE,並解釋_precisely_該代碼現在做了什麼以及您希望它做什麼。 –

回答

0

最有可能的問題是圖像分辨率,例如300 dpi,與屏幕分辨率(最可能的是96 dpi)相比。你有沒有檢查圖像的PixelWidth和PixelHeight?

+0

我的PixelWidth = 1920,PixelHeight = 1080,dpiX = 72,dpiY = 72,PixelFormat是BGR32。 但爲什麼使用ratioX和ratioY不能正確剪切? – Anton

+0

我是否需要將圖像轉換爲屏幕分辨率還是有其他解決方案? P.S.我的應用程序應該處理數千個圖像並將每個轉換爲屏幕分辨率將會非常慢解決方案 – Anton

+0

謝謝。它有幫助。 – Anton