首页 > 代码库 > Fractal Tree
Fractal Tree
尝试使用递归方式实现一棵简单的分形树,给出初始点的坐标,在此基础上根据坐标轴旋转的规则计算出子树干与根节点的坐标关系,依次递归画出左子树干和右子树干,并提供一个递归的深度用于控制画的子树的数目。
在二维坐标系中,坐标轴旋转的公式如下:
In two dimensions, every rotation matrix has the following form,
This rotates column vectors by means of the following matrix multiplication,
So the coordinates (x‘,y‘) of the point (x,y) after rotation are
参考资料见维基百科旋转矩阵:http://en.wikipedia.org/wiki/Rotation_matrix
将这个分形树的实现添加到之前的绘图框架中,只需要增加一个Tree1类,然后再FractalPanel中调用此类的draw方法即可,并且在FractalMain类中添加相关的Button操作。Tree1类的实现如下:
package com.elvalad;import java.awt.*;/** * Created by elvalad on 2015/1/4. */public class Tree1 { private double x; private double y; private double alpha; private int depth; private Color color = new Color(43, 77, 219); public Tree1(double x, double y, double alpha, int depth, Color color) { this.x = x; this.y = y; this.alpha = alpha; this.depth = depth; this.color = color; } public void draw(Graphics g) { g.setColor(this.color); this.drawShape(g, this.x, this.y, this.alpha, this.depth); } private void drawShape(Graphics g, double x1, double y1, double angle, double depth) { if (depth == 0) { } else { double x2 = x1 + Math.cos(Math.toRadians(angle)) * depth * 15.0; double y2 = y1 + Math.sin(Math.toRadians(angle)) * depth * 15.0; Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setStroke(new BasicStroke((float) (0.5f * depth))); g.drawLine((int)x1, (int)y1, (int)x2, (int)y2); drawShape(g, x2, y2, angle + 25, depth - 1); drawShape(g, x2, y2, angle - 25, depth - 1); } }}
Fractal Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。