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:
public static double calculateLengthToPaint(double angle, double heightOfSquare){
return (heightOfSquare/2.0) / Math.cos(Math.toRadians(angle));
}
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.
public static double calculateLengthToPaint(double angle, double heightOfSquare){
double flippy = angle % 90;
if (flippy > 45.0){
flippy -= 90;
flippy = Math.abs(flippy);
}
return (heightOfSquare/2.0) / Math.cos(Math.toRadians(flippy));
}
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.