首页 > 解决方案 > 如何从鼠标坐标中获得正确的像素位置?

问题描述

我正在使用e.GetPosition. 它在接近 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;
}

改变像素的图像

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

标签: c#wpfcoordinatespixel

解决方案


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

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);

    ...
}

推荐阅读