我上周一直在研究这个项目,但不知道如何解决它。我觉得我已经很接近了,但无法发现我的错误! 我的作业要求我使用 Java Graphics 类沿着假想线绘制圆圈。在圆心画一个半径为 n 的圆。然后画两个半径为n/2的圆,其端点分别与圆的左右圆弧相交。
我已经能够在第一个圆圈的右侧和左侧绘制两个圆圈的第二步。然而,我的程序应该递归地绘制四个相同大小的圆。左圆的左右两侧各一圈,右圆的左右两侧各一圈。我的代码有些可疑。
任何帮助将不胜感激。
package fractalcircles;
import java.awt.*;
import javax.swing.*;
public class FractalCircles {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{ //create a MyCanvas object
MyCanvas canvas1 = new MyCanvas();
//set up a JFrame to hold the canvas
JFrame frame = new JFrame();
frame.setTitle("FractalCircles.java");
frame.setSize(500,500);
frame.setLocation(100,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add the canvas to the frame as a content panel
frame.getContentPane().add(canvas1);
frame.setVisible(true);
}//end main
}//end class
class MyCanvas extends Canvas
{
public MyCanvas()
{} //end MyCanvas() constructor
//this method will draw the initial circle and invisible line
public void paint (Graphics graphics)
{
int x1,x2,y1,y2; //future x and y coordinates
int radius=125; //radius of first circle
int xMid=250, yMid=250; //center point (x,y) of circle
//draw invisible line
graphics.drawLine(0,250,500,250);
//draw first circle
graphics.drawOval(xMid-radius,yMid-radius,radius*2,radius*2);
//run fractal algorithm to draw 2 circles to the left and right
drawCircles(graphics, xMid, yMid, radius);
}
void drawCircles (Graphics graphics, int xMid, int yMid, int radius)
{
//used to position left and right circles
int x1 = xMid-radius-(radius/2);
int y1 = yMid-(radius/2);
int x2 = xMid+radius-(radius/2);
int y2= yMid-(radius/2);
if (radius > 5)
{
//draw circle to the left
graphics.drawOval(x1, y1, (radius/2)*2, (radius/2)*2);
//draw circle to the right
graphics.drawOval(x2, y2, (radius/2)*2, (radius/2)*2);
}
drawCircles (graphics, xMid, yMid, radius/2);
}
最佳答案
一些使用递归的改编版本... 绘制圆,然后再次调用相同的函数来绘制它的 2 个子圆。
void drawCircles(Graphics graphics, int xMid, int yMid, int radius) {
// end recursion
if(radius < 5)
return;
// Draw circle
graphics.drawOval(xMid - radius, yMid - radius, radius * 2, radius * 2);
// start recursion
//left
drawCircles(graphics, xMid-radius, yMid, radius / 2);
//right
drawCircles(graphics, xMid+radius, yMid, radius / 2);
}
关于java - 使用 Java 绘制由圆圈组成的分形图案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21867973/