I need to draw a fill square, that square must be painted with lines from center.
we can’t use java shapes
We have a center point and the pen must draw a line from center to the square edge in each angle.
The problem here is the Maths, what can i use to calculate the distance needed to paint. Because if i use always same distance it will draw a circle.
Thanks
When drawing the square you can think of the length you need to draw at any angle as being the length of the hypoteneuse of a right-angled triangle. You can solve this with trigonometric ratios easily enough. The tricky part is that the base of the triangle moves around.
Taking the example of a line at 45 degrees shown in the left half of the diagram below:
You need to work out the length of the red line (hyp). You can use
trigonometry to work out the length of hyp based on its angle to
adj and the length of the
adj. The length of the adj side is half the height of the
square.
The formula to use is:
cos(angle) = adj/hyp
rearranged:
hyp = adj/cos(angle)
The code would look something like this:
Unfortunately that’s not all though. This works perfectly for the first 45 degrees, but when angle > 45 degrees then the adjacent side of the triangle changes place (as can be seen in the right half of the diagram below). It keeps flipping over every 45 degrees.
To handle this flipping you need to use the angle that’s passed into the method (the angle around the square from the 12 o’clock position) to work out the angle of the triangle we are imagining. I’ve modified the method above to add logic to work out the corrected angle.
Notes: This code takes it’s angle in degrees and only works for positive angles. Also, if you want to have the lines meet the square at even increments around the perimiter then you need to come up with a solution that uses the pythagorean theorem to work out the length of the hypoteneuse and then use trigonometry to work out the angle to draw it at.
Hope that helps.