用JAVA画一个樱花树
时间: 2023-10-25 08:08:06 浏览: 58
很抱歉,作为AI语言模型,我无法提供绘画功能。建议您参考以下JAVA代码实现:
```
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CherryBlossomTree extends JPanel {
private static final long serialVersionUID = 1L;
private int WIDTH = 800; // 画布宽度
private int HEIGHT = 600; // 画布高度
private int maxDepth = 8; // 树的最大深度
private int trunkWidth = 50; // 树干宽度
private int branchWidth = 20; // 树枝宽度
private double branchRatio = 0.7; // 分支长度比例
private double angle = Math.PI / 4; // 分支角度
private double angleVariation = Math.PI / 4; // 角度变化范围
public static void main(String[] args) {
JFrame frame = new JFrame("Cherry Blossom Tree");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
CherryBlossomTree tree = new CherryBlossomTree();
frame.add(tree);
frame.setVisible(true);
}
public CherryBlossomTree() {
setBackground(Color.WHITE);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawTree(g, WIDTH / 2, HEIGHT, -Math.PI / 2, trunkWidth, maxDepth);
}
private void drawTree(Graphics g, int x1, int y1, double angle, double width, int depth) {
if (depth == 0) {
return;
}
int x2 = x1 + (int) (Math.cos(angle) * depth * width);
int y2 = y1 + (int) (Math.sin(angle) * depth * width);
g.setColor(new Color(139, 69, 19));
g.fillRect(x2, y2, (int) width, (int) -depth * 10);
Random r = new Random();
double angle1 = angle + r.nextDouble() * angleVariation - angleVariation / 2;
double angle2 = angle + r.nextDouble() * angleVariation - angleVariation / 2;
drawTree(g, x2, y2, angle1, width * branchRatio, depth - 1);
drawTree(g, x2, y2, angle2, width * branchRatio, depth - 1);
if (depth == 1) {
drawBlossom(g, x2, y2, 50);
}
}
private void drawBlossom(Graphics g, int x, int y, int size) {
g.setColor(Color.PINK);
g.fillOval(x - size / 2, y - size / 2, size, size);
g.setColor(Color.WHITE);
g.fillOval(x - size / 2 + size / 4, y - size / 2, size / 2, size / 2);
}
}
```
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)