Search code examples
javalinesshapestrigonometry

Drawing shapes with lines in JAVA


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: enter image description here

Problem is solved thank you for the advice guys it was my mistake with using integer casting.


Solution

  • 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.