读书人

三角中点

发布时间: 2013-07-16 22:38:05 作者: rapoo

三角形中点
1.通过循环完成三角形中点连接
ActionListener al = new ActionListener() {
// 动作事件的处理方法
public void actionPerformed(ActionEvent e) {

for (int i = 0; i < 1000; i++) {
Random rand = new Random();
int value = rand.nextInt(3);
if (value == 0) {
g.drawLine((x1 + x4) / 2, (y1 + y4) / 2, (x1 + x4) / 2,
(y1 + y4) / 2);
x4 = (x1 + x4) / 2;
y4 = (y1 + y4) / 2;
} else if (value == 1) {
g.drawLine((x2 + x4) / 2, (y2 + y4) / 2, (x2 + x4) / 2,
(y2 + y4) / 2);
x4 = (x2 + x4) / 2;
y4 = (y2 + y4) / 2;
} else if (value == 2) {
g.drawLine((x3 + x4) / 2, (y3 + y4) / 2, (x3 + x4) / 2,
(y3 + y4) / 2);
x4 = (x3 + x4) / 2;
y4 = (y3 + y4) / 2;
}
}
}
};
2.通过递归函数实现三角形中点分形
ActionListener al = new ActionListener() {
// 动作事件的处理方法
public void actionPerformed(ActionEvent e) {
Color c2= new Color(0,0,255);
g.setColor(c2);
double x1 =200,y1 =400;
double x2 =500,y2 =100;
double x3 =700,y3 =600;
sanjiao(x1,y1,x2,y2,x3,y3,6);//调用递归方法
}


public void sanjiao(double x1,double y1,double x2,double y2,double x3,double y3,double depth){
//递归函数
if(depth>=0){
g.drawLine((int)x1, (int)y1, (int)x2, (int)y2);
g.drawLine((int)x3, (int)y3, (int)x2, (int)y2);
g.drawLine((int)x1, (int)y1, (int)x3, (int)y3);
//g.drawLine((int)((x1+x2)/2), (int)((y1+y2)/2),(int) ((x2+x3)/2),(int) ((y2+y3)/2));
sanjiao(0.5*(x1+x2), 0.5*(y1+y2),x2,y2, 0.5*(x2+x3), 0.5*(y2+y3),depth-1);
//g.drawLine((int)((x1+x2)/2),(int) ((y1+y2)/2),(int) ((x1+x3)/2),(int) ((y1+y3)/2));
sanjiao(x1,y1,0.5*(x1+x2), 0.5*(y1+y2), 0.5*(x1+x3), 0.5*(y1+y3),depth-1);
//g.drawLine((int)((x1+x3)/2), (int)((y1+y3)/2), (int)((x2+x3)/2),(int) ((y2+y3)/2));
sanjiao(0.5*(x1+x3), 0.5*(y1+y3), 0.5*(x2+x3), 0.5*(y2+y3),x3,y3,depth-1);
}
}
};

读书人网 >编程

热点推荐