How to pan Image inside PictureBox

前端 未结 1 1192
渐次进展
渐次进展 2021-01-05 07:27

I have a custom PictureBox which can zoom in using MouseWheel event. Now I want to add a panning feature to it. I mean when PictureBox is in zoomed

1条回答
  •  星月不相逢
    2021-01-05 08:02

    I think the math is backwards. Try it like this:

    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);
    }
    

    You aren't disposing your graphic object, and CreateGraphics is just a temporary drawing anyway (minimizing would erase it) so I moved the drawing code to the Paint event and am just invalidating as the user is panning.

    0 讨论(0)
提交回复
热议问题