2011-10-31 145 views
2

我正在为WIA创建图像扫描应用程序。但是,如果扫描的文档尺寸不是很大,我的图像有很多未使用的空间。我需要裁剪那个​​未使用的空间,就像Paint with Cross cursor和rectangle一样。如何在WPF中做到这一点? 图像的代码裁剪是:自定义矩形的图像裁剪

private static Image cropImage(Image img, Rectangle cropArea) 
{ 
Bitmap bmpImage = new Bitmap(img); 
Bitmap bmpCrop = bmpImage.Clone(cropArea,bmpImage.PixelFormat); 
return (Image)(bmpCrop); 
} 
+0

它是什么,是抱着你回来了?你在寻找一种在图像上绘制选区的方法吗?您发布的代码是否无效? –

+0

是的,我正在寻找方式来绘制选择 –

回答

5

把图像控制在帆布和添加不可见的矩形到画布为好。

用鼠标左键将矩形的左上角设置为鼠标坐标并使其可见。

在鼠标移动(并且鼠标按钮仍然向下)的情况下,设置矩形的大小,因此第一个角的相反位置随鼠标移动。

例子:

<Window x:Class="TestWpfApplication.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:TestWpfApplication" 
     Title="MainWindow" 
     Height="350" 
     Width="525"> 
    <Canvas MouseLeftButtonDown="Canvas_MouseLeftButtonDown" 
      MouseMove="Canvas_MouseMove" 
      Background="AntiqueWhite"> 
     <Image Width="500" 
       Height="300" /> 
     <Rectangle x:Name="selectionRectangle" 
        StrokeThickness="1" 
        Stroke="LightBlue" 
        Fill="#220000FF" 
        Visibility="Collapsed" /> 
    </Canvas> 

</Window> 

而后面的代码:

using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Input; 

namespace TestWpfApplication 
{ 
    public partial class MainWindow : System.Windows.Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
     { 
      var mousePosition = e.GetPosition(sender as UIElement); 
      Canvas.SetLeft(selectionRectangle, mousePosition.X); 
      Canvas.SetTop(selectionRectangle, mousePosition.Y); 
      selectionRectangle.Visibility = System.Windows.Visibility.Visible; 
     } 

     private void Canvas_MouseMove(object sender, MouseEventArgs e) 
     { 
      if (e.LeftButton == MouseButtonState.Pressed) 
      { 
       var mousePosition = e.GetPosition(sender as UIElement); 
       selectionRectangle.Width = mousePosition.X - Canvas.GetLeft(selectionRectangle); 
       selectionRectangle.Height = mousePosition.Y - Canvas.GetTop(selectionRectangle); 
      } 
     } 
    } 
} 

注意,当它有一个颜色画布将只响应点击。

另外:您将需要处理用户将选区拖动到左侧和/或从下到上的情况,因为这会导致矩形的宽度和高度为负值。但我会把它留给你。

+1

非常感谢!为我工作。 –