gah! How to clip rotated rectangles.

BlitzMax Forums/BlitzMax Programming/gah! How to clip rotated rectangles.

Here is the code without hardcoded values. The rotate function really only works with square images with an equal number of pixels.

SuperStrict

Graphics 640,480

Local oldImage:TImage = LoadImage("tiger.png")

' generate precalc sin/cos arrays
Global sn:Float[] = New Float[360]
Global cs:Float[] = New Float[360]
For Local i:Int = 0 To 359
	sn[i] = Sin(i)
	cs[i] = Cos(i)
Next 

Local angle:Int = 0

While Not KeyHit(KEY_ESCAPE)
	Cls
	Local newImage:Timage = rotateImageClipped(oldImage,angle)
	DrawImage(oldImage,10,100)
	DrawImage(newImage,276,100)
	Flip

	angle :+ 1
	If angle > 359 Then angle :- 360

Wend
End

'
'	This function will rotate one image into another with clipping and return the rotated image when done.
'	
Function rotateImageClipped:TImage(img:TImage,angle:Int)
	Local sourcePmap:TPixmap = LockImage(img)						' lock source image and create pixmap to get data from
	Local width:Int = sourcePmap.width								' find width of image
	Local height:Int = sourcePmap.height							' find height of image
	Local destPmap:TPixmap = CreatePixmap(width,height,PF_RGBA8888)	' create destination pixmap where the rotated image is stored
	ClearPixels(destPmap)											' clear pixmap
	' define local variables used in the rotation
	Local wh:Int = (width/2)-1
	Local hh:Int = (width/2)-1
	' loop through destPmap pixels and copy from source image
	For Local y:Int = 0 To height-1
		For Local x:Int = 0 To width-1
			Local tx:Int = (x-wh) * cs[angle] - (y-hh) * sn[angle] + wh
			Local ty:Int = (y-hh) * cs[angle] + (x-wh) * sn[angle] + hh
			' test to see if within bounds of source image
			If tx > -1 And tx < width And ty > -1 And ty < height Then
				WritePixel(destPmap,x,y,ReadPixel(sourcePmap,tx,ty))
			End If
		Next
	Next
	UnlockImage(img)	' unlock source image
	Return LoadImage(destPmap)	' return the newly created image
End Function