Drawing shapes in Java using StdDraw and loops... This is some basic code I did
ID: 3864607 • Letter: D
Question
Drawing shapes in Java using StdDraw and loops...
This is some basic code I did to draw shapes:
How would I transform this into a loop to draw circles, squares, ellipses, etc.?
EDIT: I can do easy shapes like a ladder for example, however, I am having trouble making lines horizontal in a loop...
38 Std Draw. line demo 39 40 Points 41 StdDraw. settpenRadius (.03) 42 StdDraw. setPenColor (StedDraw.CYAN) 43 StdDraw point (100, 60) 44 StdDraw. setpencolor(stdDraw.cYAN) ;I 45 StdDraw.point (500, 200); 46 47 Lines (Square 48 StdDraw. settpenRadius (.01) 49 StdDraw.. setPenColor(StdDraw. YELLOW) 50 StdDraw. Line (50, 10, 250, 10) bottom 51 StdDraw. setPenColor (StedDraw. YELLOW) 52 StdDraw. Line (50, 10, 50, 173) left side 53 StdDraw. setPenColor (StedDraw. YELLOW) 54 StdDraw. Line (50, 173, 250, 173) top 55 StdDraw. setPenColor (StedDraw. YELLOW) 56 StdDraw. Line (250, 10, 250, 173) right side 58 Circles 59 StdDraw. set PenRadius (.01) 60 StdDraw. Set PenColor(StdDraw. BLACK); 61 StdDraw. circle (100, 200, 5);Explanation / Answer
Hi,
Whe we say drawing in loop we have to use some standard graphic algorithms where we use pixel as point and iterate i..e loop over pixels to draw the required figure.
For the above question , please use Bresenham's line algorithm to draw a line using pixel.
In our case the pixel will be drawn as point using function as below:
1. to Draw a point
StdDraw.setPenRadius(0.03)
StdDraw.setPenColor(StdDraw.CYAN)
StdDraw.point(x,y)
2. Now apply the Line algorithm as below using loops ( Do while here )
// Adding comments
// set pen radius
The below are the line co-ordinates (first end and the other end)
x1,y1
x2 ,y2
//start co-ordinate be as below
x = x1
y = y1
StdDraw.setPenRadius(0.03)
StdDraw.setPenColor(StdDraw.CYAN)
StdDraw.point(x,y)
// The algorithm as follows
/ get Deltas of the co-rdinates
dx = (x2 - x1);
dy = (y2 - y1);
p = 2 * (dy) - (dx); // This is Slope of the line
// Start point of the line
x = x1;
y = y1;
// The core algorithm
i = 1; // loop initialization
do {
StdDraw.setPenColor(StdDraw.CYAN)
StdDraw.point(x,y)
while(p >= 0) {
y = y + 1;
p = p - (2 * dx);
}
x = x + 1;
p = p + (2 * dy);
i = i + 1;
}
while(i <= dx);
End Result: You will get a line printed.
2. For circle . Follow the same principle of drawing the Circle and follow Bresenham Circle drawing algorithm.
3. For Squares please iterate line making module as function and drawing the four lines as the required dimension and co-odinate.
I hope the explanation helps
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.