- Calculate SIN and COS once
- Apply these in a formula to all pixels
- Do this in reverse to avoid gaps in the final image
Rotation-matrix
To rotate a pixel around an axis, we need to do some sinus and co-sinus calculation to it because, in short, rotation follows a circular path.
The good part is that the sinus and co-sinus part of the calculation remains the same for every pixel, because they all rotate the same amount.
The next code sets up the values needed later in the main loop. And C#’s math functions want to see Radians, not degrees.
double rotationRadians = userRotate * (Math.PI / 180); float sin = (float) Math.Cos(rotationRadians); float cos = (float) Math.Sin(rotationRadians);
In reverse
If we where to go over every pixel in the original image and calculate it’s new position, then there would be gaps in the destination image.
Therefore, we go over every pixel in the destination image, and calculate back where its original position is, that way we always have a pixel color when within the image’s border.
Continue reading “How to rotate an image in C#”