【发布时间】:2014-07-15 08:48:52
【问题描述】:
我在面板中绘制了一个 BufferedGraphics。图像被放大和缩小。从这个缓冲的图形图像中,我怎样才能在图像中而不是在面板中找到鼠标位置。
private void panel2_paint(object sender, PaintEventArgs e)
{
if (bitmap != null)
{
float widthZoomed = panel2.Width / Zoom;
float heigthZoomed = panel2.Height / Zoom;
if (widthZoomed > 30000.0f)
{
Zoom = panel2.Width / 30000.0f;
widthZoomed = 30000.0f;
}
if (heigthZoomed > 30000.0f)
{
Zoom = panel2.Height / 30000.0f;
heigthZoomed = 30000.0f;
}
if (widthZoomed < 2.0f)
{
Zoom = panel2.Width / 2.0f;
widthZoomed = 2.0f;
}
if (heigthZoomed < 2.0f)
{
Zoom = panel2.Height / 2.0f;
heigthZoomed = 2.0f;
}
float wz2 = widthZoomed / 2.0f;
float hz2 = heigthZoomed / 2.0f;
Rectangle drawRect = new Rectangle(
(int)(viewPortCenter.X - wz2),
(int)(viewPortCenter.Y - hz2),
(int)(widthZoomed),
(int)(heigthZoomed));
drawrecX = drawRect.X;
drawrecY = drawRect.Y;
dispwidth = (int)(widthZoomed);
dispheight = (int)(heigthZoomed);
myBuffer.Graphics.Clear(Color.White); //Clear the Back buffer
Console.WriteLine(this.panel2.DisplayRectangle.Width);
Console.WriteLine(this.panel2.DisplayRectangle.Height);
myBuffer.Graphics.DrawImage(bitmap, this.panel2.DisplayRectangle, drawRect, GraphicsUnit.Pixel);
//pictureBox1.Image =
myBuffer.Render(this.panel2.CreateGraphics());
//this.toolStripStatusLabel1.Text = "Zoom: " + ((int)(this.Zoom * 100)).ToString() + "%";
}
}
上面的代码是油漆部分。 为了在图像中找到鼠标的位置,我试过这样
private void panel2_DoubleClick(object sender, EventArgs e)
{
var mouseArgs = (MouseEventArgs)e;
double Pic_width = dispwidth / panel2.Width;//to find the relative position
double Pic_height = dispheight / panel2.Height;
int xpoint = (int)Pic_width * mouseArgs.X + drawrecX;//drawrecX is the X coordinate from the drawing image
int ypoint = (int)Pic_height * mouseArgs.Y + drawrecY;
}
但是这段代码没有给我确切的位置。有什么想法吗?
【问题讨论】:
-
您必须对鼠标位置应用相同的转换。使用 Matrix 类总是要容易得多。您可以直接将其分配给 Graphics.Transform 属性以使其对绘画有效。并再次使用它来映射鼠标位置,使用它的 TransformPoints() 方法。如有必要,从图像坐标返回鼠标位置也很容易,使用 Matrix.Invert() 方法。
-
@HansPassant 感谢您的反馈。但我不知道该怎么做。请给我一个示例代码或链接?