问题
I'm creating app for image scan with WIA. But my images has a lot of unused space if scanned document size is not big. I need to crop that unused space like in Paint with Cross cursor and rectangle. How to do that in WPF? Code of image cropping is:
private static Image cropImage(Image img, Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea,bmpImage.PixelFormat);
return (Image)(bmpCrop);
}
回答1:
Put the Image control in a Canvas and add an invisible rectangle to the canvas as well.
On left mouse button down set the top left of the rectangle at the mouse coordinates and make it visible.
On mouse move (and mouse button still down), set the size of the rectangle, so the opposite of the first corner moves with the mouse.
Example:
<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>
And the code behind:
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);
}
}
}
}
Note that the Canvas will only respond to a click when it has a color.
Also: you'll need to handle the situation where the user drags the selection right to left and/or bottom to top because that will introduce negative sizes for the width and height of the rectangle. But I'll leave that to you.
回答2:
Thanks for this code. My actual issues realted to CROP iamge show in another iamge control. How ist possible in WPF. Please fallow this link.
http://social.msdn.microsoft.com/Forums/en-US/302bb1c8-e272-48b1-982d-12cf2aefe8a3/how-to-crop-image-show-in-another-image-control-?forum=wpf
Thank
来源:https://stackoverflow.com/questions/7955026/image-crop-with-custom-rectangle