Rotate images that are scaled in C#

[rotate images]

The example Interactively rotate images in C# lets you click and drag to rotate images but it doesn’t always work well if the image you are rotating is too big to fit on the screen. The example Rotate images inside a scrolled panel in C# lets you scroll to part of a large image so you can use that part to align the image.

Sometimes, however, it might be better to see a small version of the entire image instead of a small piece of the image. This example displays a scaled version of the image and lets you rotate it.

To do that, the program displays the image in a PictureBox. In the original version of the program the PictureBox control’s ScaleMode property was set to AutoSize so the PictureBox sized itself to fit the image. If the image was too big, the PictureBox was too large to manage effectively.

In this example the PictureBox control’s SizeMode property is set to Zoom. That makes the control retain its original size and scale its image so it is as large as possible while still fitting completely inside the PictureBox.

Note that this means the image will be enlarged if it is smaller than the PictureBox. That may not be necessary but probably won’t hurt either.

The program uses mouse events to let you click and drag to rotate the image. To do that, it needs to calculate the mouse’s position relative to the center of the image. In the previous example, the program used the following code to calculate the offset from the center of the image.

float dx = e.X - ImageCenter.X;
float dy = e.Y - ImageCenter.Y;

Here ImageCenter was a point representing the center of the image. It was calculated when the result image was created.

In the new program the image has been scaled but the mouse coordinates are not scaled. That means the effective center of the image has been moved.

The new program uses the following code to calculate the offset from the mouse to the center of the image.

float dx = e.X - (picRotated.ClientSize.Width / 2f);
float dy = e.Y - (picRotated.ClientSize.Height / 2f);

Instead of using the center of the image in pixels, it uses the center of the PictureBox. The PictureBox scales and centers the image, so this is the position of the scaled image’s center.

The rest of the code is exactly the same as before. Download the example and see the previous examples for more details.


Download Example   Follow me on Twitter   RSS feed   Donate


About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in algorithms, graphics, image processing, transformations and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Rotate images that are scaled in C#

  1. maxy says:

    Good work, l lik it.

Leave a Reply

Your email address will not be published. Required fields are marked *