Home > database >  How can I rotate object in pixel grid properly?
How can I rotate object in pixel grid properly?

Time:09-28

I have an 2D grid made from 1D array with with and height property. In that grid I have a box object which I want to rotate by X amount of degrees. I have used this formula to rotate each pixel of object in grid:

newX = floor(cos(angle)*x - sin(angle)*y)
newY = floor(sin(angle)*x   cos(angle)*y)

It works fine when the box is small but if the box is bigger I get some empty cells. How can I fill empty spaces witch should be filled. Here is an example of box with width and height 10 and then rotated by 45 degrees:
Example

CodePudding user response:

Perform reverse mapping:

Walk through all pixels of result. You can use bounding box of rotated image and scan its lines.

For every pixel one get coordinates of corresponding source pixel. If they lie in valid range (source rectangle), then copy source color to result.

To get reverse mapping formula, just change angle sign (if you have pure rotation without shift)

oldx = cos(angle)*newx   sin(angle)*newy
oldy = -sin(angle)*newx   cos(angle)*newy
  • Related