2023年6月11日
How to correct the mouse down position after zooming?
c# – How to correct the mouse down position after zooming? – Stack Overflow
Based on the referred problem, to scale and offset the view to the mouse wheel position:
private float zoom = 1f;
private PointF wheelPoint;
private void picturebox_MouseWheel(object sender, MouseEventArgs e)
{
zoom += e.Delta < 0 ? -.1f : .1f;
zoom = Math.Max(.1f, Math.Min(10, zoom));
wheelPoint = new PointF(e.X * (zoom - 1f), e.Y * (zoom - 1f));
picturebox.Invalidate();
}
Offset and scale before drawing your shapes:
private void picturebox_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
g.TranslateTransform(-wheelPoint.X, -wheelPoint.Y);
g.ScaleTransform(zoom, zoom);
// Draw....
}

If you also use the mouse inputs to draw your shapes, then you also need to take the offset into account to get the right point.
Revising the first example to mainly add the ScalePoint
method to do the required calculations.
private float _zoom = 1f;
private PointF _wheelPoint;
private readonly SizeF _recSize = new Size(60, 60);
private List<RectangleF> _rects = new List<RectangleF>();
private PointF ScalePoint(PointF p) =>
new PointF(
(p.X + _wheelPoint.X) / _zoom - (_recSize.Width / 2),
(p.Y + _wheelPoint.Y) / _zoom - (_recSize.Height / 2));
private void picturebox_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_rects.Add(new RectangleF(ScalePoint(e.Location), _recSize));
picturebox.Invalidate();
}
}
private void picturebox_MouseWheel(object sender, MouseEventArgs e)
{
_zoom += e.Delta < 0 ? -.1f : .1f;
_zoom = Math.Max(.1f, Math.Min(10, _zoom));
_wheelPoint = new PointF(e.X * (_zoom - 1f), e.Y * (_zoom - 1f));
picturebox.Invalidate();
}
private void picturebox_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
g.TranslateTransform(-_wheelPoint.X, -_wheelPoint.Y);
g.ScaleTransform(_zoom, _zoom);
g.SmoothingMode = SmoothingMode.AntiAlias;
_rects.ForEach(r => g.FillEllipse(Brushes.Black, r));
}
