How to pan an image inside a PictureBox

I have a custom PictureBox that can zoom in with the MouseWheel event. Now I want to add a pan function to it. I mean, when the PictureBox is in an enlarged state, if the user left the clicks and holds the click, then move the mouse, the image will pan in the image window.

Here is my code, but unfortunately it doesn't work! I don’t know where to look for more ...

 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 + eX; var ny = _panStartingPoint.Y + eY; var sourceRectangle = new Rectangle(nx, ny, Image.Width, Image.Height); g.DrawImage(Image, nx, ny, sourceRectangle, GraphicsUnit.Pixel); } } 

I suspect a MouseMove ... I'm not sure if something is happening in this event and / or nx and ny contains the correct point.

Any hints / tips are really appreciated!

+7
source share
1 answer

I think the math is back. Try this as follows:

 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 are not deleting your graphic object, and CreateGraphics is just a temporary drawing (minimizing it will erase it), so I moved the drawing code to the Paint event and is simply invalid when the user panes.

+11
source

All Articles