如何泛内PictureBox的Image(How to pan Image inside Pictu

2019-06-27 05:15发布

我有一个自定义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事件......我不知道,如果有什么事情发生在这个事件和/或nxny确实包含正确的点。

任何帮助/提示真的appriciated!

Answer 1:

我认为数学是倒退。 试着这样说:

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事件和我只是作为无效用户平移。



文章来源: How to pan Image inside PictureBox