Search code examples
javaandroidarrayspixelgeometry

Java draw pixel circle in 2D array


I have this code:

void drawCircle(int x, int y, int r, int color) {
    double PI = 3.1415926535;
    double i, angle, x1, y1;

    for (i = 0; i < 360; i += 1) {
        angle = i;
        x1 = r * cos(angle * PI / 180);
        y1 = r * sin(angle * PI / 180);

        int ElX = (int) (x + x1);
        int ElY = (int) (y + y1);
        myPixelElements[ElX][ElY].setElementColor(color);
    }
}

It almost works but for some reason it draws 2 dots wrong:

Circle it draws


Solution

  • cos and sin functions produce double values from -1 to +1, and when you cast double to int like this: int ElX = (int) (x + x1), some data will be inevitably lost, because such cast just chops the decimal part away. Instead, I suggest rounding double with Math.round, check example below:

    System.out.println((int) 0.99);            //  0
    System.out.println((int) -0.99);           //  0
    System.out.println(Math.round(0.99));      //  1
    System.out.println(Math.round(-0.99));     // -1
    

    Note that Math.round returns long, so it still must be casted to int:

    int ElX = (int) Math.round(x + x1);
    int ElY = (int) Math.round(y + y1);
    

    Output

       Before              After
    
       ******              *****      
      *      *           ***   ***    
     *        *          *       *    
     *        *         **       **   
     *        *         *         *   
     *        **        *         *   
     *        *         *         *   
     *        *         **       **   
      *      *           *       *    
       ******            ***   ***    
          *                *****