Вопрос

I have a image editing program and need the X and the Y coordinate of the image. At the moment I use the MouseLeftButtonDown and MouseRightButtonDown event.

<Image Name="Image" MouseLeftButtonDown="MouseLeftButtonDown_Click" MouseRightButtonDown="MouseRightButtonDown_Click"></Image>

The problem I have is that I don't geht the right position on the picture in my WPF form. Means, if I drag the window smaller the coordinate is changing.

My method looks like this:

private void MouseLeftButtonDown_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    System.Windows.Point p = e.GetPosition(null);
    MessageBox.Show(p.X.ToString());
}

I think that the problem is that I add null as a argument in e.GetPosition. But I don't know what I have to add here otherwise...

For example I open a 1920x1080 image I really want 1920 and 1080 if I press the mouse at the right bottem corner.

Это было полезно?

Решение

Sounds as if you want the position with respect to the pixels of the original image, no matter what size the containing window is.

This should help...

private void MouseLeftButtonDown_Click(object sender, MouseButtonEventArgs e)
{
    System.Windows.Point p = e.GetPosition(image);
    double pixelWidth = image.Source.Width;
    double pixelHeight = image.Source.Height;
    double x = pixelWidth * p.X / image.ActualWidth;
    double y = pixelHeight * p.Y / image.ActualHeight;
    MessageBox.Show(x + ", " + y);
}

I renamed your image to "image" to resolve the conflict between image name and class name. Update your XAML as follows:

<Image Name="image" MouseLeftButtonDown="MouseLeftButtonDown_Click" MouseRightButtonDown="MouseRightButtonDown_Click"></Image>

pixelWidth and pixelHeight are the original width and height of the source image. x and y are calculated according the ratio between the original pixel width/height and the actual displayed width/height of the image on screen.

To display whole pixels in the popup message, use this instead:

MessageBox.Show((int)x + ", " + (int)y);

@Gerret: please can you give a few examples of the wrong coordinates, and what you were expecting them to be?

Другие советы

instead of null try passing your Image

Like System.Windows.Point p = e.GetPosition(Image);

For Example:

Your Image:

<Image x:Name="imgYouImage" /> 

In your code use:

Point p = e.GetPosition(imgYouImage);

Try:

System.Windows.Point p = e.GetPosition(Image);

As recommended by Simon Martin, I'll explain this...

GetPosition() returns the position of the mouse click in relation to the position of the element passed in as an argument. If you pass in null, this will be relative to the position of the window, so you need to pass in your image name to get the correct coordinates.

Please see my other answer for a better solution.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top