2011-10-31 144 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

非常感謝!爲我工作。 –