Valhalla Legends Forums Archive | General Programming | Rotating an Image

AuthorMessageTime
Mr. Neo
I am working on rotating some images for a simple little game.  Currently, I have working code that will rotate an image 90, 180, or 270 degrees.  When I use this same code to rotate an image, say 45 degrees, the image gets distorted and cut off.  Example:
[img]http://www.filefarmer.com/dimmensionx/rotate.gif[/img]

For the rotation, I'm using the formulas:
DestinationX = Cos(Degrees) * (OriginalX - OriginX) - Sin(Degrees) * (OriginalY - OriginY)
DestinationY = Sin(Degrees) * (OriginalX - OriginX) + Cos(Degrees) * (OriginalY - OriginY)

I just loop through every pixel in the original image and redraw it on a new image.  My code for this is:
[code]
  For i=-1 To Image.Width
    For n=-1 To Image.Height
      pnt.X = i
      pnt.Y = n
     
      rpnt = RotatePoint(pnt,originpnt,Amount)
     
      If rpnt.X > maxx Then
        maxx = rpnt.X
      End if
     
      If rpnt.Y > maxy Then
        maxy = rpnt.Y
      End If
     
      pict.RGBSurface.Pixel(rpnt.X,rpnt.Y) = Image.RGBSurface.Pixel(i,n)
     
    Next
  Next
 
  final = NewPicture(maxx,maxy,32)
  final.Graphics.DrawPicture pict,0,0
[/code]

Image is holding the original picture, and pict is holding the rotated image as it is being assembled.  This is in REALbasic.

If there is a better algorithm for rotating pictures, I'd be extremely interested in knowing it.  Any insight into this would be greatly appreciated.
September 14, 2005, 2:37 AM
Adron
You should probably iterate over the destination pixels and pick what source pixel to use. You may want to interpolate over several source pixels. For your image getting cut off, what coordinates is it getting cut off at? zero?
September 14, 2005, 2:45 PM
Myndfyr
If you can invoke the Win32 API, you might consider using GDI+.

Very generally, you'll want to create a Matrix object and set its Rotate value.  Then you'll create an Image object with your image (probably via your image handle).  You'll then create a Graphics object, and then use the DrawImage function that supports using a Matrix parameter.  You'll be using handles through all this since you're using REALBasic.  Take a look at the "GDI+ Flat API" -- it enables use of the GDI+ interface through the Win32 API instead of using classes.
September 14, 2005, 4:08 PM

Search