使用Java2D绘制3D House?

时间:2010-11-24 03:00:37

标签: java graphics graphics2d

如何使用Java2D绘制简单的3D房屋?我想绘制房子的侧壁,使它看起来像一个简单的3D绘图。

// House.java

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GradientPaint;
import java.awt.geom.Rectangle2D;

public class House extends Canvas{

  House(){
    setSize(800,600);
  }
  public void paint(Graphics g){

    // house - foundation
    g.setColor(new Color(0xCDBE70));
    g.fillRect(148,500,304,50);

    // house - front
    g.setColor(new Color(0xFFEC8B));
    g.fillRect(150,350,300,150);

    // house - side 
    }    
  }

// ShowHouse.java

import java.awt.Frame; 
import java.awt.AWTEvent;
import java.awt.event.WindowEvent;

public class ShowHouse extends Frame{ 
  public static void main(String arg[]){
    new ShowHouse(); 
  }
  ShowHouse(){ 
    enableEvents(AWTEvent.WINDOW_EVENT_MASK); 
    setLocation(250,50);
    House canvas = new House();
    add(canvas);
    pack(); 
    setVisible(true);
  }
  public void processWindowEvent(WindowEvent event){
    if(event.getID() == WindowEvent.WINDOW_CLOSING) 
      System.exit(0);
  }
  }

1 个答案:

答案 0 :(得分:1)

我改写了你的House Class:

// House.java

public class House extends Canvas{

  House(){
    setSize(800,600);
  }
  public void paint(Graphics g){

    Polygon p = new Polygon();
    p.addPoint(100,50);
    p.addPoint(300,50);
    p.addPoint(250,100);
    p.addPoint(50,100);

    g.fillPolygon(p);

    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(new Color(0xAEAEAE));
    g2.draw(new Line2D.Double(300, 50, 350, 100));
    g2.draw(new Line2D.Double(350, 100, 350, 180));
    g2.draw(new Line2D.Double(350, 180, 250, 180));
    g.setColor(new Color(0xFFEABB));
    p = new Polygon();
    p.addPoint(50,100);
    p.addPoint(250,100);
    p.addPoint(250,180);
    p.addPoint(50,180);

    g.fillPolygon(p);

    g.setColor(new Color(0xFFFFFF));
    p = new Polygon();
    p.addPoint(75,125);
    p.addPoint(225,125);
    p.addPoint(225,150);
    p.addPoint(75,150);

    g.fillPolygon(p);

    }
  }