gpt4 book ai didi

java - 使用 Java 绘制由圆组成的分形图案

转载 作者:行者123 更新时间:2023-11-30 09:11:55 26 4
gpt4 key购买 nike

上周我一直在处理这个项目,但不知道如何修复它。我觉得我很接近但无法发现我的错误!我的作业要求我使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com