如何在PictureBox中平移图像

7

我有一个自定义的PictureBox控件,可以使用MouseWheel事件进行缩放。现在我想添加一个平移功能。我的意思是当PictureBox处于放大状态时,如果用户左键单击并保持点击状态,然后移动鼠标,图像将在picturebox内平移。

以下是我的代码,但不幸的是它无法工作!我不知道还要看哪里...

private Point _panStartingPoint = Point.Empty;
private bool _panIsActive;

private void CurveBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Focus();
        _panIsActive = true;
        _panStartingPoint = e.Location;
    }
}

private void CurveBox_MouseUp(object sender, MouseEventArgs e)
{
    _panIsActive = false;
}

private void CurveBox_MouseLeave(object sender, EventArgs e)
{
    _panIsActive = false;

}

private void CurveBox_MouseMove(object sender, MouseEventArgs e)
{
    if(_panIsActive && IsZoomed)
    {
        var g = CreateGraphics(); //Create graphics from PictureBox

        var nx = _panStartingPoint.X + e.X;
        var ny = _panStartingPoint.Y + e.Y;
        var sourceRectangle = new Rectangle(nx, ny, Image.Width, Image.Height);
        g.DrawImage(Image, nx, ny, sourceRectangle, GraphicsUnit.Pixel);
    }
}

我怀疑是MouseMove事件...我不确定这个事件中是否有任何操作,以及nxny是否包含了正确的坐标点。

非常感谢任何帮助和提示!

1个回答

15

我认为数学是反过来了,尝试像这样:

private Point startingPoint = Point.Empty;
private Point movingPoint = Point.Empty;
private bool panning = false;

void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
  panning = true;
  startingPoint = new Point(e.Location.X - movingPoint.X,
                            e.Location.Y - movingPoint.Y);
}

void pictureBox1_MouseUp(object sender, MouseEventArgs e) {
  panning = false;
}

void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
  if (panning) {
    movingPoint = new Point(e.Location.X - startingPoint.X, 
                            e.Location.Y - startingPoint.Y);
    pictureBox1.Invalidate();
  }
}

void pictureBox1_Paint(object sender, PaintEventArgs e) {
  e.Graphics.Clear(Color.White);
  e.Graphics.DrawImage(Image, movingPoint);
}

你没有将图形对象释放,而且CreateGraphics只是一个临时的绘图方式(最小化会擦除它),所以我将绘图代码移动到Paint事件中,并在用户移动时仅作无效处理。


在“e.Graphics.DrawImage(Image, movingPoint);”中,“Image”被定义为什么? - Kraang Prime
@SanuelJackson 图像是在表单级别声明的图像变量。显然,命名选择不佳;应该被命名为myImage或类似的名称。 - LarsTech

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