码迷,mamicode.com
首页 > 其他好文 > 详细

Fractal Tree

时间:2015-01-05 23:09:40      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

尝试使用递归方式实现一棵简单的分形树,给出初始点的坐标,在此基础上根据坐标轴旋转的规则计算出子树干与根节点的坐标关系,依次递归画出左子树干和右子树干,并提供一个递归的深度用于控制画的子树的数目。

在二维坐标系中,坐标轴旋转的公式如下:

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

标签:

原文地址:http://www.cnblogs.com/elvalad/p/4204773.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!