简体   繁体   中英

How can a draw a circle in java pixel by pixel using a graphical app?

The applet used is like the first quadrant of a Cartisian Plane with the domain and range (0, 200). My assignment is to draw a house and a sun in this applet. I am trying to draw the circle for the sun. I really have no idea where to start. We are learning about for loops and nested loops so it probably pertains to that. We haven't got to arrays and general functions like draw.circle do not exist for this applet. If it helps, here is how I drew my roof for the house (two right triangles): Notice it is drawn pixel by pixel. I suspect my teacher wants the same kind of thing for the circle.

//roof
//left side
double starty = 100;
for(double x = 16; x <= 63; x++){
        for(int y = 100; y <= starty; y++){
               img.set(x, y, JRaster.purple);
        }
starty += 1;
}

//right side
double startx = 110;
for(int y = 100; y <= 147; y++){
       for(double x = 63; x <= startx; x++){
               img.set(x , y, JRaster.purple);
       }
startx -= 1;
}

I won't give you code, but you should remember how a circle is made. Going from theta=0 to theta=2*pi, the circle is traced by x=cos x , y=sin x .

So, using a for loop that increments a double(here called theta) by something like 0.01 until 2*pi( 2*Math.PI or roughly 6.28) plot off Math.cos(theta), Math.sin(theta) .

Here's how I would draw the north-east quarter of a circle, pixel by pixel. You can just repeat this with slight variations for the other three quarters. No trigonometry required!

  • Start by drawing the eastern most point of the circle. Then you'll draw more pixels, moving northwards and westwards, until you get to the northern most point of the circle.
  • Calculate the distance of the point you've just drawn from the centre. If it's more than the radius, then your next pixel will be one to the left, otherwise, your next pixel will be the one above.
  • Repeat the previous step till you get to the northern most point.

Post a comment if you get stuck, with converting this to Java, or with adjusting it for the other three quarters of the circle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM