有没有更好的方法来绘制像这样的空心立方体?

时间:2011-03-16 12:31:16

标签: java-me canvas

这是我使用两个方块绘制空心立方体的代码。还有什么好主意吗?

import javax.microedition.midlet.*; 
import javax.microedition.lcdui.*;

public class CanvasUnit extends Canvas {

    String SOutput;

    public CanvasUnit(String TextToPrint) {
        //SOutput = TextToPrint;
        SOutput = "This is a hollow cube";
    } 

    public void paint(Graphics g) {

        int width = getWidth();
        int height = getHeight();
        int WLen = width / 4;
        int HLen = height / 4;
        int WPosA = (WLen * 2);
        int HPosA = (HLen * 2);
        int WPosB = (WPosA+WLen/2);
        int HPosB = (HPosA+HLen/2);

        //Clear the screen
        g.setColor(0,0,0);
        g.fillRect(0, 0, width, height);
        g.setColor(255,255,255);
        g.drawString(SOutput,0,0,Graphics.TOP|Graphics.LEFT);

        //Object1
        g.drawLine(WLen, HLen, WPosA, HLen);
        g.drawLine(WLen, HLen, WLen, HPosA);
        g.drawLine(WLen, HPosA, WPosA, HPosA);
        g.drawLine(WPosA, HLen, WPosA, HPosA);

        //--------------------------------------------

        //Object2
        g.drawLine(Ex(WLen), Ex(HLen), WPosB, Ex(HLen));
        g.drawLine(Ex(WLen), Ex(HLen), Ex(WLen), HPosB);
        g.drawLine(Ex(WLen), HPosB, WPosB, HPosB);
        g.drawLine(WPosB, Ex(HLen), WPosB, HPosB);

        //--------------------------------------------

        //Connector Lines
        g.drawLine(WLen, HLen, Ex(WLen), Ex(HLen));
        g.drawLine(WPosA, HLen, WPosB, Ex(HLen));
        g.drawLine(WLen, HPosA, Ex(WLen), HPosB);
        g.drawLine(WPosA, HPosA, WPosB, HPosB);

    }
        private int Ex(int value){
       return value + (value/2);    }


}

输出: Output : http://up.iranblog.com/images/ttfhinrbao6hvlkko8uk.png

1 个答案:

答案 0 :(得分:1)

更好的方式:

    //Draw two hollow squares
    g.drawRect(WLen, HLen, WLen, HLen);
    g.drawRect(Ex(WLen), Ex(HLen), WLen, HLen);
    //Connector Lines
    g.drawLine(WLen, HLen, Ex(WLen), Ex(HLen));
    g.drawLine(WPosA, HLen, WPosB, Ex(HLen));
    g.drawLine(WLen, HPosA, Ex(WLen), HPosB);
    g.drawLine(WPosA, HPosA, WPosB, HPosB);