如何从鼠标坐标获得正确的像素位置?

How to get correct position of pixel from mouse coordinates?

我正在使用 e.GetPosition 获取鼠标坐标。 returns接近0的坐标是正确的,但是我离图片右上角越远越不准

我希望能够点击一个像素并改变它的颜色。但现在它改变了另一个像素,而不是我点击的像素(0,0 处除外)。

 private void image_MouseDown(object sender, MouseButtonEventArgs e)
 {
       // coordinates are now available in p.X and p.Y
       var p = e.GetPosition(image);

       System.Drawing.Color red = System.Drawing.Color.FromArgb(255, 0, 0);

       //converting to bitmap
       MemoryStream outStream = new MemoryStream();

       BitmapEncoder enc = new BmpBitmapEncoder();
       enc.Frames.Add(BitmapFrame.Create(wBitmap));
       enc.Save(outStream);
       System.Drawing.Bitmap img = new System.Drawing.Bitmap(outStream);

       //calculating pixel position
       double pixelWidth = image.Source.Width;
       double pixelHeight = image.Source.Height;
       double dx = pixelWidth * p.X / image.ActualWidth;
       double dy = pixelHeight * p.Y / image.ActualHeight;

       //converting to int
       int x = Convert.ToInt32(dx);
       int y = Convert.ToInt32(dy);
           
       img.SetPixel(x, y, red);

       //putting it back to writable bitmap and image    
       wBitmap = BitmapToImageSource(img);
       image.Source = wBitmap;
}

image with changed pixel

我想改变图像中这样的像素。然而,它并没有改变我点击的那个像素,而是另一个更远一点的像素。

为了获取 Image 元素上的鼠标事件在 Source 位图中的像素位置,您必须使用 BitmapSource 的 PixelWidthPixelHeight 而不是 Width 和身高:

private void ImageMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var image = (Image)sender;
    var source = (BitmapSource)image.Source;
    var mousePos = e.GetPosition(image);

    var pixelX = (int)(mousePos.X / image.ActualWidth * source.PixelWidth);
    var pixelY = (int)(mousePos.Y / image.ActualHeight * source.PixelHeight);

    ...
}