【发布时间】:2015-04-22 09:29:42
【问题描述】:
所以我正在实现一个可以读取图像平移、缩放和做其他事情的项目。一切都很顺利,直到我尝试用鼠标右键实现绘图。
问题是当我画一条线时,出现在图像上的线与我在屏幕上画的线不对应,这意味着它发生了偏移,我知道它是因为图像的重新调整大小和缩放,但是当我在图像上用其原始大小(图像)和平移画线时;我没问题。
这是代码。
首先这里是当我点击浏览并选择图片时如何加载图片
Myimage = new Bitmap(ImagePath);
resized = myImage.Size;
imageResize();
pictureBox.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox_Paint);
pictureBox.Invalidate();
imageResize 函数执行以下操作:
void imageResize()
{
//calculated the size to fit the control i will draw the image on
resized.Height = someMath;
resized.Width = someMath;
}
然后在我写的 pictureBox_Paint 事件的事件处理程序中:
private void pictureBox_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
// Create a local version of the graphics object for the PictureBox.
Graphics PboxGraphics = e.Graphics;
PboxGraphics.DrawImage(myImage, imageULcorner.X, imageULcorner.Y, resized.Width, resized.Height);
}
如您所见,调整后的大小不是原始图像大小,我这样做是因为我希望图像显示在图片框控件上集中并填充现在下一部分是我的问题开始的地方
我必须使用鼠标右键在图像上画线,所以我实现了 pictureBox_MouseDown 和 pictureBox_MouseUp 事件处理程序
// mouse down event handler
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
else if (mouse.Button == MouseButtons.Right)
{
mouseDown = mouse.Location;
mouseDown.X = mouseDown.X - imageULcorner.X;
mouseDown.Y = mouseDown.Y - imageULcorner.Y;
draw = true;
}
}
这里是鼠标向上事件处理程序
//Mouse UP
private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
else if (mouse.Button == MouseButtons.Right)
{
if (draw)
{
mouseLocationNow.X = mouse.X - imageULcorner.X;
mouseLocationNow.Y = mouse.Y - imageULcorner.Y;
//
// get graphics object of the image ( the original not the resized)
// as the resized image only appears when i draw on the graphics of the
// pictureBox control
// i know the problem lies here but how can i fix it
//
Graphics image = Graphics.FromImage(myImage);
Pen pen = new Pen(Color.Red, 2);
image.DrawLine(pen, mouseLocationNow, mouseDown);
pictureBox.Invalidate();
}
draw = false;
}
所以最后我希望能够在调整大小的图像上绘制并使其与真实图像以及我画线的屏幕相对应 感谢和抱歉发了这么长的帖子,但这个问题让我发疯了。
【问题讨论】:
-
简短版本是:您需要 a) 计算鼠标事件中的点以适应缩放(向后,因为您瞄准的是缩放的世界)和 b) 缩放图形对象(向前,使用矩阵变换)到与图片框中的图像相同的缩放比例。
-
如果您愿意使用 WPF,我过去曾问过类似的问题。问题和答案可能会有所帮助 - stackoverflow.com/questions/14729853/…
-
@TaW 我知道 (A) 但我不知道 (B) 存在...听起来像是找到解决方案的好方法...谢谢。
-
使用
Matrix来完成缩放(这是一个好主意),然后您也可以获得逆矩阵并使用它将用户输入的鼠标坐标转换回您的坐标空间图片。基本上,您最终在原始图像坐标空间中完成所有实际工作,使用矩阵将用户输入转换回图像坐标空间,并从图像坐标空间(即图像本身和任何其他渲染在Paint事件期间将其顶部(例如选择矩形)返回到屏幕。 -
虽然我猜你可以独自处理彼得和我给你的提示,但我认为添加一个代码示例以供将来参考也不会受到伤害..
标签: c# winforms graphics zooming line