Reputation: 163
So I am having a big problem with drawing shapes using only lines. Lets say I start to draw a line from a point on the middle of the screen and draw it forward at 100 distance in pixels and with angle 0 then I draw another line of the same length using angle 72 degrees and so on until 360 degrees. It should give me perfect pentagon where one line ends and another starts from that point, but the lines do not meet on the end it works perfect for squares where angles are 0/90/180/270 but I need to make it work for each shape even circles. I am using this thing for calculations:
_endingPointX = (_currentPostisionX + distance * _cosinuses[_angle]);
_endingPointY = (_currentPostisionY + distance * _sinuses[_angle]);
Where _cosinuses and _sinuses are arrays of doubles that contain the values for sinuses and cosinuses for each one of 360 degrees. And when drawing a line I need to cast these values to integer.
drawLine(_currentPostisionX, _currentPostisionY, (int) _endingPointX, (int) _endingPointY);
I do not know how to fix this and make the lines meet at the end of drawn shape. Been trying to figure out this for a few days but nothing comes to my mind.
Here is a screenshot:
Problem is solved thank you for the advice guys it was my mistake with using integer casting.
Upvotes: 1
Views: 1324
Reputation: 28727
Calculate all values in double and round immediately before drawing.
Do not calculate further with the rounded ones.
To draw a pentagon or a n- gon use something similar to:
// number of corners of pentagon
double numVertex = 5;
// how much to change the angle for the next corner( of the turtle )
double angleStep = 360.0 / numVertex;
gc.moveTo(cx, cy - rad);
for (int i= 1; i < numVertex; i++) {
// total angle from 0 degrees
double angle = i* angleStep;
// px point of turtle is corner of pentagon
double px = cx + rad * sin(angle * DEG_TO_RADIANS);
// move turtle to
gc.lineto((int)Math.round(px),
(int)Math.round(py));
}
gc.lineTo(cx, cy - rad);
If you use lineTo
instead line chances are higher that the points meet.
Upvotes: 2
Reputation: 22817
If you just rely on int
values, you will have accuracy issues because sin(72°)
is irrational, while sin(90°)
is not of course.
But you can draw Line2D
in both double
or float
precision, or use GeneralPath
[which uses float
].
Upvotes: 0
Reputation: 452
It does not perfectly line up due to rounding errors resulting from precision of sin and cos functions. To fix this, you can store the starting point as a separate variable, and use it as an ending point for the last line.
Upvotes: 0