转换鼠标坐标

5

我正在制作一个图形程序,但我卡在需要让鼠标坐标等于图形比例的地方。使用picturebox时,我使用transform来缩放我的图形:

RectangleF world = new RectangleF(wxmin, wymin, wwid, whgt);
        PointF[] device_points =
            {
                new PointF(0, PictureBox1.ClientSize.Height),
                new PointF(PictureBox1.ClientSize.Width, PictureBox1.ClientSize.Height),
                new PointF(0, 0),
            };
        Matrix transform = new Matrix(world, device_points);
        gr.Transform = transform;

在此输入图像描述 我正在使用MouseMove函数。有没有一种方法可以转换鼠标坐标?当我把鼠标放在x = 9上时,我需要我的鼠标坐标为9。

private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        Console.WriteLine(e.X);
    }

2
不要忘记transform。你会喜欢它的Invert()方法,方便将鼠标坐标映射回图形坐标。 - Hans Passant
1个回答

3
正如Hans的评论所暗示的那样,您可以使用第二个Matrix来实现这一点。您可以通过复制原始的Matrix并调用副本的Invert()方法来获得它,或者您可以通过从原始矩形中反转输入矩形来创建新的Matrix
在我看来,倒置更容易,但这意味着您需要创建逆矩阵并将其存储在某个地方。例如:
    Matrix transform = new Matrix(world, device_points);
    gr.Transform = transform;
    inverseTransform = transform.Clone();
    inverseTransform.Invert();

其中,inverseTransform 是您类中的一个字段而不是局部变量,因此您的鼠标处理代码稍后可以使用它。
如果您必须稍后构建 Matrix,可以按以下方式执行:
RectangleF device = new RectangleF(new Point(), PictureBox1.ClientSize);
PointF[] world_points =
    {
        new PointF(wxmin, wymin + whgt),
        new PointF(wxmin + wwid, wymin + whgt),
        new PointF(wxmin, wymin),
    };
Matrix inverseTransform = new Matrix(device, world_points);

在任一情况下,你只需要在鼠标处理代码中使用 Matrix.TransformPoints() 方法来应用逆转换到鼠标坐标,以返回到你的世界坐标。

我做了这个,但它返回相同的X和Y值。`inverseTransform = transform.Clone(); inverseTransform.Invert(); List location = new List(); Point p = new Point(e.X, e.Y); location.Add(p); inverseTransform.TransformPoints(location.ToArray()); Console.WriteLine("location = " + location[0]);` - WhizBoy
2
根据您在此处的评论:点值是就地转换的。您创建了一个新数组来传递给TransformPoints()方法,但是您直接将其传递给该方法,而不保留对它的引用。因此,该方法会转换点,但您无法获取新值。请尝试Point[] location = { new Point(e.X, e.Y) }; inverseTransform.TransformPoints(location); - Peter Duniho

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接