---
title: " 分形之——谢尔宾斯基三角形"
author: "心若吾心"
date: "2013-11-30T17:53:57Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-11-30T17:53:57Z"
id: 1983255
url: "https://982677720.iteye.com/blog/1983255"
---

分形之——谢尔宾斯基三角形

现实中我们画不出的一些图形，在机器的世界里可以尽情发挥无限的想象力让计算机来帮我们完成。比如说著名谢尔宾斯基三角形 。如果人工去画这样一副图，不仅是不标准的，而且还要花上大量的时间。所以计算机的“”死脑筋”和极快的速度可以得到人类很好的利用。
递归：一个巧妙的工具，虽然它在时间复杂度上比较令人头疼，但是用它来做一些东西仍是不错的选择。这里我们演示一下谢尔宾斯基三角形的做法。


源代码：
package testAng;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class FrameListener implements MouseListener {

	private Graphics g;
	private Color c1 = Color.red;
	private Color c2 = Color.yellow;
	private Color c3 = Color.blue;

	/**
	 * 带参数的构造方法
	 */
	public FrameListener(Graphics g) {
		this.g = g;
	}

	/**
	 * 画出分形图形
	 */
	public void mouseClicked(MouseEvent e) {
		// 调用画分形的方法
		drawAng(8, g, 300, 60, 30, 500, 570, 500, 0);
	}

	/**
	 * 递归画歇尔滨斯基三角形
	 * 
	 * @param count循环次数
	 * @param g画布
	 * @param x1
	 * @param y1
	 * @param x2
	 * @param y2
	 * @param x3
	 * @param y3
	 * @param R红色
	 * @param G黄色
	 * @param B蓝色
	 */
	public void drawAng(int count, Graphics g, int x1, int y1, int x2, int y2,
			int x3, int y3, int type) {
		count--;
		// count>0 递归 否则返回
		if (count < 1) {
			return;
		}
		if (type == 1) {
			g.setColor(c1);
		}
		if (type == 2) {
			g.setColor(c2);
		}
		if (type == 3) {
			g.setColor(c3);
		}
		g.drawLine(x1, y1, x2, y2);
		g.drawLine(x1, y1, x3, y3);
		g.drawLine(x2, y2, x3, y3);
		int x4 = (x1 - x2) / 2 + x2;
		int y4 = (y2 - y1) / 2 + y1;
		int x5 = (x3 - x1) / 2 + x1;
		int y5 = (y3 - y1) / 2 + y1;
		int x6 = (x3 - x2) / 2 + x2;
		int y6 = (y3 - y2) / 2 + y2;
		drawAng(count, g, x1, y1, x4, y4, x5, y5, 1);
		drawAng(count, g, x4, y4, x2, y2, x6, y6, 2);
		drawAng(count, g, x5, y5, x6, y6, x3, y3, 3);

	}

	// 以下是用不到的方法，可以必须实现MouseListener接口中的这些方法
	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub

	}

}


//另一个类，运行用
package testAng;

import java.awt.Graphics;

public class ang extends javax.swing.JFrame {

	/**
	 * 初始化界面
	 */
	public void init() {
		// 设置窗体属性
		this.setSize(600, 600);
		this.setDefaultCloseOperation(3);
		this.setVisible(true);
		Graphics g = this.getGraphics();
		java.awt.event.MouseListener l = new FrameListener(g);
		this.addMouseListener(l);

	}

	public static void main(String args) {
		ang a = new ang();
		a.init();
	}
}