c# - 如何从鼠标坐标中获得正确的像素位置?
问题描述
我正在使用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;
}
我想在图像中更改这样的像素。然而,它并没有改变我点击的像素,而是另一个更远一点的像素。
解决方案
为了获取Source
图像元素上鼠标事件位图中的像素位置,您必须使用 BitmapSource 的PixelWidth
andPixelHeight
而不是 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);
...
}
推荐阅读
- javascript - 如何获得比数组javascript的其他元素更大的3个对象
- css - 绝对定位的工具提示(在:之前)被标题栏截断
- vba - 尝试通过从设计器中的 ControlSource 调用函数来填充 Access ContinuousForm 中的 ComboBox(每行不同的记录集)
- c# - 通过反射访问模型类的布尔值并访问它们的值
- visual-studio-2019 - 使用多个 IsEmbedded 引用时的验证错误
- node.js - Blob Storage Azure 和 javascript,如何列出特定 blob 的所有快照
- python - python kmeans 聚类真实数据质心
- mysql - 如何在mysql中按给定年份计算月份和成员明智总数
- powershell - Powershell AD 脚本无法导出到 csv
- multithreading - Parallel For-Each vs Scatter Gather in mule