从屏幕上的鼠标光标位置获取图像坐标(WPF 图像控件)
我一直在寻找一种解决方案来透明地添加平移和;WPF 图像控件的缩放功能,我找到了解决方案 https://stackoverflow.com/a/6782715/584180,由 Wiesław Šoltés 和 Konrad Viltersten,非常出色.
I was looking for a solution to transparently add panning & zooming capability to a WPF Image control and I have found the solution https://stackoverflow.com/a/6782715/584180, developed by Wiesław Šoltés and Konrad Viltersten, which is outstanding.
现在我想给控件添加一个鼠标点击"事件,这样我就可以在原始图像坐标系中获得点击点的坐标,这样我就可以使用它们来检索像素颜色.
Now I would like to add a 'mouse click' event to the control so that I can the coordinates of the clicked point in the original image coordinate system, so I can use them to retrieve the pixel color.
我知道会有一些四舍五入,如果图像被缩小,颜色将与屏幕上显示的实际颜色不符.我也知道用户可能会在图像边框外单击,在这种情况下,我希望返回空点或负坐标.
I understand there will be some rounding and if the image is zoomed out the color will not correspond to the actual one displayed on screen. I also understand that the user may click outside the image borders, in that case I expect a null Point or negative coords to be returned.
我不是 C# 转换方式的专家,目前我坚持使用这个方法(添加到 ZoomBorder.cs 类中):
I am not an expert of the C# way of doing transforms and at the moment I am stuck with this (to be added inside the ZoomBorder.cs class):
public Point GetImageCoordsAt(MouseButtonEventArgs e)
{
if (child != null)
{
var tt = GetTranslateTransform(child);
var mousePos = e.GetPosition(this);
var transformOrigin = new Point(tt.X, tt.Y);
return mousePos; // Wrong: how do I transform this?
}
return null;
}
正如 mm8 建议的那样,您可以使用 e.GetPosition(child);
获取您想要的位置,无需执行任何转换.出于测试目的,我覆盖了重置行为.使用您提供的链接中的代码,更改
As mm8 suggests you can get the location you want using e.GetPosition(child);
, there's no need to perform any transformations. For testing purposes I've overwritten the reset behaviour. Using the code from the link you provided, change
void child_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
this.Reset();
}
到
public Point GetImageCoordsAt(MouseButtonEventArgs e)
{
if (child != null && child.IsMouseOver)
{
return e.GetPosition(child);
}
return new Point(-1, -1);
}
void child_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show(GetImageCoordsAt(e).ToString());
}
如果您在图像中的同一位置右键单击,无论平移和缩放如何,您都将获得(大约)相同的坐标.
If you rightclick at the same location in the image, you'll get (approximately) the same coordinates, regardless of the pan and zoom.