1、先画一个小立方体,三个面填充不一样的颜色
2、再由小立方体搭成一个3 * 3 * 3的立方体
3、以上图立方体为最小单位,递归画出更大的立方体
先填充三面颜色,用Polygon类,再画边线。
public class ShapeLFT {
public void drawLFT(Graphics g,int x,int y){//画立方体的类
g.setColor(new Color(100,255,100));
g.fillRect(x, y, 30,30);//正面填充颜色
//顶
Polygon pon1=new Polygon();//四个顶点连成面
pon1.addPoint(x, y);
pon1.addPoint(x+15, y-15);
pon1.addPoint(x+30+15, y-15);
pon1.addPoint(x+30, y);
g.setColor(new Color(188,255,166));
g.fillPolygon(pon1);//填充
//右侧面
Polygon pon2=new Polygon();
pon2.addPoint(x+30, y);
pon2.addPoint(x+30+15, y-15);
pon2.addPoint(x+30+15, y+30-15);
pon2.addPoint(x+30, y+30);
g.setColor(new Color(150,255,133));
g.fillPolygon(pon2);
//画边框
g.setColor(new Color(60,255,20));
//顶
g.drawLine(x, y, x+15, y-15);//左上
g.drawLine(x+30, y, x+30+15, y-15);//右上
g.drawLine(x+15, y-15, x+30+15, y-15);//上
//右侧面
g.drawLine(x+30, y+30, x+30+15, y+30-15);//下
g.drawLine(x+30+15, y-15, x+30+15, y+30-15);//右
//正面
g.drawLine(x, y, x+30, y);//
g.drawLine(x+30, y, x+30, y+30);
g.drawLine(x+30, y+30, x, y+30);
g.drawLine(x, y+30, x, y);
}
根据一个小立方体的顶点坐标,推算其他小立方体的左上角的点的坐标,调用画小立方体的函数画出三层的立方体
public void drawShapeOne(Graphics g,int x,int y){
//第一层
drawLFT(g,x+15+15,y-15-15);//后左
drawLFT(g,x+15+15+30,y-15-15);//后中
drawLFT(g,x+15+15+30+30,y-15-15);//后右
drawLFT(g,x+15,y-15);//中左
drawLFT(g,x+30+30+15,y-15);//中右
drawLFT(g,x,y);//前左
drawLFT(g,x+30,y);//前中
drawLFT(g,x+30+30,y);//前右
//第二层
drawLFT(g,x+15+15,y-15-15-30);//后左
drawLFT(g,x+15+15+30+30,y-15-15-30);//后右
drawLFT(g,x,y-30);//前左
drawLFT(g,x+30+30,y-30);//前右
//第三层
drawLFT(g,x+15+15,y-15-15-60);//后左
drawLFT(g,x+15+15+30,y-15-15-60);//后中
drawLFT(g,x+15+15+30+30,y-15-15-60);//后右
drawLFT(g,x+15,y-15-60);//中左
drawLFT(g,x+30+30+15,y-15-60);//中右
drawLFT(g,x,y-60);//前左
drawLFT(g,x+30,y-60);//前中
drawLFT(g,x+30+30,y-60);//前右
}
递归到最小的部分3 * 3 * 3立方体就画出来,否则就将大的分成小的来画
立方体左上角的坐标是画立方体传递的参数,要根据当前立方体的边长来算坐标
public void draw(Graphics g,int x,int y,int k){//k为立方体的边的长度,最小的立方体边长设为30
if(k==90){//递归到3*3*3的立方体,调用函数画出
drawShapeOne(g,x,y);
return;
}
else{
k=k/3;//先画小的立方体,小的边长是大的边长除以3
//递归调用画出小的立方体
//第一层
draw(g,x+k,y-k,k);//后左
draw(g,x+k+k,y-k,k);//后中
draw(g,x+k+k*2,y-k,k);//后右
draw(g,x+k/2,y-k/2,k);//中左
draw(g,x+k+k+k/2,y-k/2,k);//中右
draw(g,x,y,k);//前左
draw(g,x+k,y,k);//前中
draw(g,x+k*2,y,k);//前右
//第二层
draw(g,x+k,y-k-k,k);//后左
draw(g,x+k+k*2,y-k-k,k);//后右
draw(g,x,y-k,k);//前左
draw(g,x+k*2,y-k,k);//前右
//第三层
draw(g,x+k,y-k-k*2,k);//后左
draw(g,x+k+k,y-k-k*2,k);//后中
draw(g,x+k+k*2,y-k-k*2,k);//后右
draw(g,x+k/2,y-k/2-k*2,k);//中左
draw(g,x+k*2+k/2,y-k/2-k*2,k);//中右
draw(g,x,y-k*2,k);//前左
draw(g,x+k,y-k*2,k);//前中
draw(g,x+k*2,y-k*2,k);//前右
}