【发布时间】:2022-01-01 16:04:39
【问题描述】:
我的问题与How to get correct position of pixel from mouse coordinates? 类似,但需要注意的是图像可能是TransformedBitmap,可以在其中应用翻转和旋转,并且仍然返回原始图像的像素坐标。
我的Window 的设计是这样的:
<DockPanel>
<Label DockPanel.Dock="Bottom" Name="TheLabel" />
<Image DockPanel.Dock="Top" Name="TheImage" Stretch="Uniform" RenderOptions.BitmapScalingMode="NearestNeighbor" MouseMove="TheImage_MouseMove" />
</DockPanel>
代码隐藏如下:
public MainWindow()
{
InitializeComponent();
const int WIDTH = 4;
const int HEIGHT = 3;
byte[] pixels = new byte[WIDTH * HEIGHT * 3];
pixels[0] = Colors.Red.B;
pixels[1] = Colors.Red.G;
pixels[2] = Colors.Red.R;
pixels[(WIDTH * (HEIGHT - 1) + (WIDTH - 1)) * 3 + 0] = Colors.Blue.B;
pixels[(WIDTH * (HEIGHT - 1) + (WIDTH - 1)) * 3 + 1] = Colors.Blue.G;
pixels[(WIDTH * (HEIGHT - 1) + (WIDTH - 1)) * 3 + 2] = Colors.Blue.R;
BitmapSource bs = BitmapSource.Create(WIDTH, HEIGHT, 96.0, 96.0, PixelFormats.Bgr24, null, pixels, WIDTH * 3);
TheImage.Source = bs;
}
private void TheImage_MouseMove(object sender, MouseEventArgs e)
{
Point p = e.GetPosition(TheImage);
if (TheImage.Source is TransformedBitmap tb)
TheLabel.Content = tb.Transform.Inverse.Transform(new Point(p.X * tb.PixelWidth / TheImage.ActualWidth, p.Y * tb.PixelHeight / TheImage.ActualHeight)).ToString();
else if (TheImage.Source is BitmapSource bs)
TheLabel.Content = new Point(p.X * bs.PixelWidth / TheImage.ActualWidth, p.Y * bs.PixelHeight / TheImage.ActualHeight).ToString();
}
当悬停在未转换图像的右下角(我将其涂成蓝色以便于跟踪)时,您可以正确看到 (~4, ~3) 的坐标,即图像尺寸。
但是,一旦您应用了转换,例如将 TheImage.Source = bs; 更改为 TheImage.Source = new TransformedBitmap(bs, new RotateTransform(90.0));,将鼠标悬停在蓝色上就会得到 (~4, ~0)。
我认为可以查看变换的实际矩阵值,并确定如何在所有各种情况下调整点,但似乎应该有一个使用逆变换更简单的解决方案。
【问题讨论】:
标签: c# .net wpf image bitmapsource