Code archives/Graphics/Rotate a hollow box

This code has been declared by its author to be Public Domain code.

Download source code

Rotate a hollow box by TAS2013
Seems like there should be a simpler way to do this (without using an image).
Graphics 800,600
Cls 
SetBlend SOLIDBLEND
SetColor 200,200,200
SetScale 2,2
DrawRect 200,200,100,50
SetColor 255,0,0
SetHandle 0,0
SetLineWidth 2
Rot_Box(200,200,100,50,45)
Rot_Box(200,200,100,50,90)
Rot_Box(200,200,100,50,180)

Flip
WaitKey()


Function RotX#(x#,y#,deg#)
	Return x*Cos(deg)-y*Sin(deg)
End Function

Function RotY#(x#,y#,deg#)
	Return x*Sin(deg)+y*Cos(deg)
End Function

Function Rot_Box(bx#,by#,w#,h#,deg#)
	'bx,by == upper right corner
	'draw a box rotated about its center
	Local s1#,s2#
	GetScale(s1,s2)
	SetScale 1,1
	w=w/2*s1
	h=h/2*s2
	'calc center of rectangle
	x=bx+w
	y=by+h
	'calc corner points after rotating about center
	x1=x+RotX#(-w,-h,deg)
	y1=y+RotY#(-w,-h,deg)
	x2=x+RotX#( w,-h,deg)
	y2=y+RotY#( w,-h,deg)
	x3=x+RotX#(-w, h,deg)
	y3=y+RotY#(-w, h,deg)
	x4=x+RotX#( w, h,deg)
	y4=y+RotY#( w, h,deg)

	'draw the box
	DrawLine x1,y1,x2,y2
	DrawLine x1,y1,x3,y3
	DrawLine x2,y2,x4,y4
	DrawLine x3,y3,x4,y4
	'restore scale
	SetScale s1,s2
End Function

Comments

Jesse2013
it can be done with only two trig function calls plus without the rot function calls will be quite a bit faster.


Floyd2013
Exploiting the symmetry of a rectangle you only need to rotate one vertex.

Suppose that (x,y) is one corner of a (possibly rotated) rectangle centered at the origin.
The other three corners are then (-y,x), (-x,-y) and (y,-x).

Just add (c,d) to each of these to move the rectangle so it is centered at (c,d).


Jesse2013
@Floyd

my logic tells me that only works for squares not rectangles. I could be wrong, Haven't tested it.


TAS2013
I need to know where the corners are to detect resizing events but if have a better way please post or add a link.


Jesse2013
I kind of thought you would figure it out easy.

only two trig functions, no function calls and only two sides(corners) calculated:



now if you are actually scalling the box and measurements don't scale the drawing, scale the corners.


dw8172015
I was looking at your program, TAS. If you don't wanna do it with all those calculations, you can let BlitzMAX's own SetRotation take over, but yes, it takes an image - created & destroyed on the spot.

Might be easier to understand though.

Quick & Dirty Rotating Rectangles:

One thing I noticed, the diagonals do not get thin but maintain the correct size as the straight lines.


Code Archives Forum