Reputation: 29
I've been researching fractals and decided to give it a try, but immediately ran into a much simpler issue. I can't draw a line at any angle other than 0, 45, 90, ... etc.
The problem: My angle is an integer, and I'm using Math.toRadians(angle) to calculate the angle itself as its drawn. When I draw the line, I have to cast (int) to the double produced from Math.toRadians(), which causes me to lose the angle itself and I believe is what prevents the line from being drawn.
The code I'm using: `
Graphics2D g2d = (Graphics2D) g;
int angle = 90;
int startX = getWidth()/2;
int startY = getHeight()/2;
int length = 100;
int endX = startX + (int)Math.cos(Math.toRadians(angle)) * length;
int endY = startY + (int)Math.sin(Math.toRadians(angle)) * length;
g2d.drawLine(startX, startY, endX, endY);
`
Solution:
Graphics2D g2d = (Graphics2D) g;
int angle = 91;
int startX = getWidth()/2;
int startY = getHeight()/2;
int length = 100;
int endX = startX + (int)(Math.cos(Math.toRadians(angle)) * length);
int endY = startY + (int)(Math.sin(Math.toRadians(angle)) * length);
g2d.drawLine(startX, startY, endX, endY);
Thanks guys!
Upvotes: 1
Views: 1924
Reputation: 31290
For best precision, use Math.round():
int endX = startX + (int)Math.round(Math.cos(Math.toRadians(angle)) * length);
int endY = startY + (int)Math.round(Math.sin(Math.toRadians(angle)) * length);
You may not notice any difference in your drawing on screen, but lost precision can add up to visible glitches.
Upvotes: 1
Reputation: 6419
You are a victim of operator precedency. You need
int endX = startX + (int) (Math.cos(Math.toRadians(angle)) * length);
int endY = startY + (int) (Math.sin(Math.toRadians(angle)) * length);
Upvotes: 2