Zoom and translate an Image from the mouse location

Solution 1:

A few suggestions and a couple of tricks.
Not exactly tricks, just some methods to speed up the calculations when more than one graphic transformation is in place.

  1. Divide and conquer: split the different graphics effects and transformations in different, specialized, methods that do one thing. Then design in a way that makes it possible for these methods to work together when needed.

  2. Keep it simple: when Graphics objects need to accumulate more than a couple of transformations, the order in which Matrices are stacked can cause misunderstandings. It's simpler (and less prone to generate weird outcomes) to calculate some generic transformations (translate and scale, mostly) beforehand, then let GDI+ render already pre-cooked objects and shapes.
    Here, only Matrix.RotateAt and Matrix.Multiply are used.
    Some notes about Matrix transformations here: Flip the GraphicsPath

  3. Use the right tools: for example, a Panel used as canvas is not exactly the best choice. This Control is not double-buffered; this feature can be enabled, but the Panel class is not meant for drawing, while a PictureBox (or a non-System flat Label) supports it on its own.
    Some more notes here: How to apply a fade transition effect to Images

The sample code shows 4 zoom methods, plus generates rotation transformations (which work side-by-side, don't accumulate).
The Zoom modes are selected using an enumerator (private enum ZoomMode):

Zoom modes:

  • ImageLocation: Image scaling is performed in-place, keeping the current Location on the canvas in a fixed position.
  • CenterCanvas: while the Image is scaled, it remains centered on the Canvas.
  • CenterMouse: the Image is scaled and translated to center itself on the current Mouse location on the Canvas.
  • MouseOffset: the Image is scaled and translated to maintain a relative position determined by the initial location of the Mouse pointer on the Image itself.

You can notice that the code simplifies all the calculations, applying translations exclusively relative to the Rectangle that defines the current Image bounds and only in relation to the Location of this shape.
The Rectangle is only scaled when the calculation needs to preemptively determine what the Image size will be after the Mouse Wheel has generated the next Zoom factor.

Visual sample of the implemented functionalities:

GDI+ Zoom and Rotations Samples

Sample code:

  • canvas is the Custom Control, derived from PictureBox (you can find its definition at the bottom). This control is added to the Form in code, here. Modify as needed.
  • trkRotationAngle is the TrackBar used to define the current rotation of the Image. Add this control to the Form in the designer.
  • radZoom_CheckedChanged is the event handler of all the RadioButtons used to set the current Zoom Mode. The value these Controls set is assigned in their Tag property. Add these controls to the Form in the designer.

using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Windows.Forms;

public partial class frmZoomPaint : Form
{
    private float rotationAngle = 0.0f;
    private float zoomFactor = 1.0f;
    private float zoomStep = .05f;

    private RectangleF imageRect = RectangleF.Empty;
    private PointF imageLocation = PointF.Empty;
    private PointF mouseLocation = PointF.Empty;

    private Bitmap drawingImage = null;
    private PictureBoxEx canvas = null;
    private ZoomMode zoomMode = ZoomMode.ImageLocation;

    private enum ZoomMode
    {
        ImageLocation,
        CenterCanvas,
        CenterMouse,
        MouseOffset
    }

    public frmZoomPaint()
    {
        InitializeComponent();
        string imagePath = [Path of the Image];
        drawingImage = (Bitmap)Image.FromStream(new MemoryStream(File.ReadAllBytes(imagePath)));
        imageRect = new RectangleF(Point.Empty, drawingImage.Size);

        canvas = new PictureBoxEx(new Size(555, 300));
        canvas.Location = new Point(10, 10);
        canvas.MouseWheel += canvas_MouseWheel;
        canvas.MouseMove += canvas_MouseMove;
        canvas.MouseDown += canvas_MouseDown;
        canvas.MouseUp += canvas_MouseUp;
        canvas.Paint += canvas_Paint;
        Controls.Add(canvas);
    }

    private void canvas_MouseWheel(object sender, MouseEventArgs e)
    {
        mouseLocation = e.Location;
        float zoomCurrent = zoomFactor;
        zoomFactor += e.Delta > 0 ? zoomStep : -zoomStep;
        if (zoomFactor < .10f) zoomStep = .01f;
        if (zoomFactor >= .10f) zoomStep = .05f;
        if (zoomFactor < .0f) zoomFactor = zoomStep;

        switch (zoomMode) {
            case ZoomMode.CenterCanvas:
                imageRect = CenterScaledRectangleOnCanvas(imageRect, canvas.ClientRectangle);
                break;
            case ZoomMode.CenterMouse:
                imageRect = CenterScaledRectangleOnMousePosition(imageRect, e.Location);
                break;
            case ZoomMode.MouseOffset:
                imageRect = OffsetScaledRectangleOnMousePosition(imageRect, zoomCurrent, e.Location);
                break;
            default:
                break;
        }
        canvas.Invalidate();
    }

    private void canvas_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left) return;
        mouseLocation = e.Location;
        imageLocation = imageRect.Location;
        canvas.Cursor = Cursors.NoMove2D;
    }

    private void canvas_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left) return;
        imageRect.Location = 
            new PointF(imageLocation.X + (e.Location.X - mouseLocation.X),
                       imageLocation.Y + (e.Location.Y - mouseLocation.Y));
        canvas.Invalidate();
    }

    private void canvas_MouseUp(object sender, MouseEventArgs e) => 
        canvas.Cursor = Cursors.Default;

    private void canvas_Paint(object sender, PaintEventArgs e)
    {
        var drawingRect = GetDrawingImageRect(imageRect);

        using (var mxRotation = new Matrix())
        using (var mxTransform = new Matrix()) {

            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            e.Graphics.PixelOffsetMode = PixelOffsetMode.Half;

            mxRotation.RotateAt(rotationAngle, GetDrawingImageCenterPoint(drawingRect));
            mxTransform.Multiply(mxRotation);

            e.Graphics.Transform = mxTransform;
            e.Graphics.DrawImage(drawingImage, drawingRect);
        }
    }

    private void trkRotationAngle_ValueChanged(object sender, EventArgs e)
    {
        rotationAngle = trkAngle.Value;
        canvas.Invalidate();
        canvas.Focus();
    }

    private void radZoom_CheckedChanged(object sender, EventArgs e)
    {
        var rad = sender as RadioButton;
        if (rad.Checked) {
            zoomMode = (ZoomMode)int.Parse(rad.Tag.ToString());
        }
        canvas.Focus();
    }

    #region Drawing Methods

    public RectangleF GetScaledRect(RectangleF rect, float scaleFactor) => 
        new RectangleF(rect.Location,
        new SizeF(rect.Width * scaleFactor, rect.Height * scaleFactor));

    public RectangleF GetDrawingImageRect(RectangleF rect) => 
        GetScaledRect(rect, zoomFactor);

    public PointF GetDrawingImageCenterPoint(RectangleF rect) => 
        new PointF(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);

    public RectangleF CenterScaledRectangleOnCanvas(RectangleF rect, RectangleF canvas)
    {
        var scaled = GetScaledRect(rect, zoomFactor);
        rect.Location = new PointF((canvas.Width - scaled.Width) / 2,
                                   (canvas.Height - scaled.Height) / 2);
        return rect;
    }

    public RectangleF CenterScaledRectangleOnMousePosition(RectangleF rect, PointF mousePosition)
    {
        var scaled = GetScaledRect(rect, zoomFactor);
        rect.Location = new PointF(mousePosition.X - (scaled.Width / 2),
                                   mousePosition.Y - (scaled.Height / 2));
        return rect;
    }

    public RectangleF OffsetScaledRectangleOnMousePosition(RectangleF rect, float currentZoom, PointF mousePosition)
    {
        var currentRect = GetScaledRect(imageRect, currentZoom);
        if (!currentRect.Contains(mousePosition)) return rect;
        
        float scaleRatio = currentRect.Width / GetScaledRect(rect, zoomFactor).Width;

        PointF mouseOffset = new PointF(mousePosition.X - rect.X, mousePosition.Y - rect.Y);
        PointF scaledOffset = new PointF(mouseOffset.X / scaleRatio, mouseOffset.Y / scaleRatio);
        PointF position = new PointF(rect.X - (scaledOffset.X - mouseOffset.X), 
                                     rect.Y - (scaledOffset.Y - mouseOffset.Y));
        rect.Location = position;
        return rect;
    }

    #endregion
}

The simple PictureBoxEx custom control (modify and extend as needed):
This PictureBox is selectable, so it can be focused, with a Mouse click

using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

[DesignerCategory("Code")]
public class PictureBoxEx : PictureBox
{
    public PictureBoxEx() : this (new Size(200, 200)){ }
    public PictureBoxEx(Size size) {
        SetStyle(ControlStyles.Selectable | ControlStyles.UserMouse, true);
        BorderStyle = BorderStyle.FixedSingle;
        Size = size;
    }
}