How to get correct position of pixel from mouse coordinates?(如何从鼠标坐标中获取像素的正确位置?)
本文介绍了如何从鼠标坐标中获取像素的正确位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用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;
}
image with changed pixel
我想更改图像中的一个像素,如下所示。然而,它并没有改变我点击的像素,而是另一个更高一点的像素。
推荐答案
若要获取图像元素上鼠标事件的Source
位图内的像素位置,必须使用位图的PixelWidth
和PixelHeight
,而不是宽度和高度:
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);
...
}
这篇关于如何从鼠标坐标中获取像素的正确位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何从鼠标坐标中获取像素的正确位置?


基础教程推荐
猜你喜欢
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01