Home > Backend Development > C++ > How to Correctly Zoom and Pan an Image from the Mouse Location in C#?

How to Correctly Zoom and Pan an Image from the Mouse Location in C#?

DDD
Release: 2024-12-30 20:18:12
Original
587 people have browsed it

How to Correctly Zoom and Pan an Image from the Mouse Location in C#?

Zooming and Translating an Image from the Mouse Location

Issue Description

When trying to zoom and scale an image from the mouse location, the image jumps and fails to scale from the relocated origin. Rotation, scale, and pan functions correctly without translating to the mouse location.

Implementation

To achieve zooming and translating an image from the mouse location, we employ the following strategies:

  • TranslateTransform: Translates the bitmap to the mouse position.
  • ScaleTransform: Scales the image according to the zoom factor.
  • TranslateTransform: Translates the image back to its original position.
  • TranslateTransform: Translates the image based on pan position.

Code

private void pnl1_Paint(object sender, PaintEventArgs e)
{
    // Apply rotation angle @ center of bitmap
    e.Graphics.TranslateTransform(img.Width / 2, img.Height / 2);
    e.Graphics.RotateTransform(ang);
    e.Graphics.TranslateTransform(-img.Width / 2, -img.Height / 2);

    // Apply scaling factor - focused @ mouse location
    e.Graphics.TranslateTransform(mouse.X, mouse.Y, MatrixOrder.Append);
    e.Graphics.ScaleTransform(zoom, zoom, MatrixOrder.Append);
    e.Graphics.TranslateTransform(-mouse.X, -mouse.Y, MatrixOrder.Append);

    // Apply drag (pan) location
    e.Graphics.TranslateTransform(imgX, imgY, MatrixOrder.Append);

    // Draw "bmp" @ location
    e.Graphics.DrawImage(img, 0, 0);
}
Copy after login

Suggestions

  • Divide and conquer the transformations into specialized methods.
  • Use a custom PictureBox with double-buffering (e.g., PictureBoxEx).
  • Utilize Matrix.RotateAt and Matrix.Multiply for efficient transformations.

The above is the detailed content of How to Correctly Zoom and Pan an Image from the Mouse Location in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template