Bob
Bob

Reputation: 142

draw an angled square using sine and cosine

this is my first time posting on a forum. But I guess I will just jump in and ask.. I am trying to draw a rectangle with x, y, width, height, and angle. I do not want to create a graphics 2D object and use transforms. I'm thinking that's an inefficient way to go about it. I am trying to draw a square with rotation using a for loop to iterate to the squares width, drawing lines each iteration at the squares height. My understanding of trig is really lacking so... My current code draws a funky triangle. If there is another question like this with an answer sorry about the duplicate. If you have got any pointers on my coding I would love some corrections or pointers.

/Edit: Sorry about the lack of a question. I was needing to know how to use sine and cosine to draw a square or rectangle with a rotation centered at the top left of the square or rectangle. By using sin and cos with the angle to get the coordinates (x1,y1) then using the sin and cos functions with the angle plus 90 degrees to get the coordinates for (x2,y2). Using the counter variable to go from left to right drawing lines from top to bottom changing with the angle.

for (int s = 0; s < objWidth; s++){

       int x1 = (int)(s*Math.cos(Math.toRadians(objAngle)));
       int y1 = (int)(s*Math.sin(Math.toRadians(objAngle)));

       int x2 = (int)((objWidth-s)*Math.cos(Math.toRadians(objAngle+90)));
       int y2 = (int)((objHeight+s)*Math.sin(Math.toRadians(objAngle+90)));

       b.setColor(new Color((int)gArray[s]));
       b.drawLine(objX+x1, objY+y1, objX+x2, objY+y2);

}

Upvotes: 2

Views: 3150

Answers (2)

stackdaemon
stackdaemon

Reputation: 349

Do you mean like a "rhombus"? http://en.wikipedia.org/wiki/Rhombus (only standing, so to speak)

If so, you can just draw four lines, the horizontal ones differing in x by an amount of xdiff = height*tan(objAngle).

So that your rhombus will be made up by lines with points as

p1 = (objX,objY) (lower left corner)
p2 = (objX+xdiff,objY+height) (upper left corner)
p3 = (objX+xdiff+width,objY+height) (upper right corner)
p4 = (objX+xdiff+width,objY) (lower right corner)

and you will draw lines from p1 to p2 to p3 to p4 and back again to p1.

Or did you have some other shape in mind?

Upvotes: 0

maximus
maximus

Reputation: 4302

It is called the Rotation matrix. If your lines has the following coordinates before rotation:

line 1: (0, 0) - (0, height)

line 2: (1, 0) - (1, height)

...

line width: (width, 0) - (width, height)

Then applying the rotation matrix transform will help you:

for (int s = 0; s < objWidth; s++){
  int x1 = cos(angle)*s
  int y1 = sin(angle)*s

  int x2 = s * cos(angle) - objHeight * sin(angle)
  int y2 = s * sin(angle) + objHeight * cos(angle) 

//the rest of code
}

Hope I didn't make a mistakes.

Upvotes: 2

Related Questions