2016-08-19 242 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