Introduction
I was working on an Etch A Sketch like program and made a knob image and wanted to simply rotate it as the user hit the arrow keys. I found many sources online, but none that got it done just how I wanted (see links below in References section). I then decided since I figured it out and got it all working why not make a simple demo with source that others could use.
Background
- Loading an image from a dialogue prompt
- Creating bitmaps, image/draw updates, and Graphic manipulation
Using the Code
There is a class called Utilities
in the Utilities.cs file that contains the functions for rotating an image from the center or given an offset to rotate from.
Here is the main rotation function RotateImage
:
public static Bitmap RotateImage(Image image, PointF offset, float angle)
{
if (image == null)
throw new ArgumentNullException("image");
Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
Graphics g = Graphics.FromImage(rotatedBmp);
g.TranslateTransform(offset.X, offset.Y);
g.RotateTransform(angle);
g.TranslateTransform(-offset.X, -offset.Y);
g.DrawImage(image, new PointF(0, 0));
return rotatedBmp;
}
And here is how it is used:
Image image = new Bitmap("Picture.png");
pictureBox.Image = (Bitmap)image.Clone();
Image oldImage = pictureBox.Image;
pictureBox.Image = Utilities.RotateImage(image, 35);
if (oldImage != null)
{
oldImage.Dispose();
}
Points of Interest
Graphics
are very powerful and allow you to do image manipulation really easily. For instance, this code could easily be modified to scale instead. I may added to this with more utilities like that.
References
History
- 16th February, 2010: Initial post