7

我有一个PictureBox可以使用MouseWheel事件放大的自定义。现在我想为它添加一个平移功能。我的意思是当 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事件...我不确定此事件中是否发生任何事情和/或nx是否ny包含正确的点。

任何帮助/提示都非常有用!

4

1 回答 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 事件并且只是在用户平移时失效。

于 2012-08-21T16:16:32.913 回答