Here's how you achieve it (description below):
Variables
Paint code
private void m_Picturebox_Canvas_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.Transform = transform; }
Scroll code
protected override void OnMouseWheel(MouseEventArgs mea) { m_Picturebox_Canvas.Focus(); if (m_Picturebox_Canvas.Focused == true && mea.Delta != 0) { ZoomScroll(mea.Location, mea.Delta > 0); } }
Zoom function
//FUNCTION FOR MOUSE SCROL ZOOM-IN private void ZoomScroll(Point location, bool zoomIn) { // make zoom-point (cursor location) our origin transform.Translate(-location.X, -location.Y); // perform zoom (at origin) if(zoomIn) transform.Scale(s_dScrollValue, s_dScrollValue); else transform.Scale(1 / s_dScrollValue, 1 / s_dScrollValue); // translate origin back to cursor transform.Translate(location.X, location.Y); m_Picturebox_Canvas.Invalidate(); }
Description
First of all, as you can see, I combined the two scaling methods with one method: ZoomScroll Otherwise, we will duplicate a lot of logic ...
So what is being done here? I think itβs clear that we also need to apply the translation to the Graphics object. We "accumulate" all the transformations applied to the PictureBox in the Matrix field.
You have successfully scaled your image, but always with the beginning (upper left corner of the PictureBox ) as the local center of your zoom operation - this is how Scale / ScaleTransform ! Therefore, to scale to another, you must perform the following steps:
- translate the world, so the point you want to scale is a new origin (for example, your cursor is at
12|34 , so we translate to -12|-34 ) - now that the desired spot is our new origin, scale
- move the world back, so the starting point will again be under your cursor.
source share