我有一个显示图像的图像查看器.我想使用鼠标在图像上绘制一个矩形,并获取矩形(X1,X2,Y1和Y2)的x和y坐标.我将使用这些坐标来创建搜索区域,并在数组中找到两个像素中像素数均与图像相同的最大值和最小值.
任何人都可以引导我指引开始的方向吗?
解决方法:
您应该使用画布来显示图像并在其上绘制一个矩形.
例:
MainWindow.xaml:
<Window x:Class="CanvasRectangleSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow">
<Grid>
<Canvas x:Name="SampleImageCanvas"
MouseMove="SampleImageCanvas_MouseMove"
MouseDown="SampleImageCanvas_MouseDown"
Width="512" Height="389">
<Canvas.Background>
<!--Here you set the image to display -> You probably want to bind it to something. -->
<ImageBrush x:Name="SampleImage" Stretch="Uniform" ImageSource="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg">
</ImageBrush>
</Canvas.Background>
<!-- Here you draw whatever you want on the canvas. -->
<!-- You'll probably want to bind its width and height to something too. -->
<Rectangle x:Name="ROI" Stroke="#FFF1133E" Width="50" Height="50"/>
</Canvas>
</Grid>
</Window>
MainWindow.xaml.cs:
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
namespace CanvasRectangleSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
this.DataContext = this;
InitializeComponent();
}
// Handling the redrawing of the rectangle according to mouse location
private void SampleImageCanvas_MouseMove(object sender, MouseEventArgs e)
{
//get mouse location relative to the canvas
Point pt = e.MouseDevice.GetPosition(sender as Canvas);
//here you set the rectangle loction relative to the canvas
Canvas.SetLeft(ROI, pt.X - (int)(ROI.Width / 2));
Canvas.SetTop(ROI, pt.Y - (int)(ROI.Height / 2));
}
private void SampleImageCanvas_MouseDown(object sender, MouseButtonEventArgs e)
{
//Here you should handle saving the rectangle location
//don't forget to calculate the proportion between Canvas's size and real Image's size.
}
}
}
如果需要,可以使用if表达式将矩形重定位到画布区域,以检查画布区域是否包含鼠标位置