第三課•手機遊戲圖形技術
圖形座標系統
座標系統是用 XY 數值來指出螢幕上的任何位置,MIDP座標系統的原點 (0,0) 是在畫布的左上角,從原點開始,往右是遞增的正 X 值,往下是遞增的 Y 值。因此,在 MIDP 的所有座標數值,都是正整數。
色彩系統
JAVA所使用的是 RGB 色彩系統,是利用不同強度的紅色、綠色、及藍色來合成各種獨特的顏色,紅綠藍每一種色彩元素的強度,都是以 0 到 255 之間的數值來表示。﹝可參考 http://www.rgb-game.com/﹞
在 J2ME 中的圖形處理
要呼叫 Graphics 物件上的方法來處理圖形, Graphics 物件會被傳入到 paint( ) 方法中,進行圖形化輸出,以下是 Graphics 三大類可處理的類型:
繪製圖形原件
直線 - void drawLine (int x1, int y1, int x2, int y2)
(x1, y1) 是直線的起點,(x2, y2) 是終點
例子:
public void paint (Graphics g) {
g.drawLine(5, 10, 15, 55);
}
矩形 - void drawRect (int x, int y, int width, int height)
(x, y) 是矩形左上角的位置,width 是矩形的寬度,height是矩形的高度
例子:
public void paint (Graphics g) {
g.drawRect(5, 10, 15, 55);
}
弧形 - void drawArc (int x, int y, int width, int height, int startAngle, int arcAngle)
先想像一個矩形,在其中畫一個弧,startAngle 是弧形的開始角度,arcAngle 是迴旋角度,正的 arcAngle 是逆時方向的,而負的 arcAngle 是順時方向的。
例子:
public void paint (Graphics g) {
g.drawArc(5, 10, 150, 75, 95, 115);
}
繪製文字訊息
用 Graphics 中的 drawString( ) 方法:
void drawString(String str, int x, int y, int anchor)
str 是文字訊息,(x,y) 是指定文字訊息的座標,anchor是文字訊息的水平和垂直的定位情況
例子:
g.drawString("Hello", getWidth( ) / 2, 0, Graphics.HCENTER | Graphics.TOP);
文字訊息的 x, y 是在畫面頂端與中線所交集而成的位置﹝getWidth( ) / 2﹞,文字訊息會以 x, y 位置的 x 部份為基準,以水平置中的方式繪製,文字頂端會對齊 x, y 位置所指定的 y 座標位置。
繪製影像圖片
Image類別中,有一個叫 createImage( ) 的方法以載入圖片:
public static Image createImage(String name) throws IOException
Graphics 提供了一個可以繪圖的方法:
boolean drawImage(Image img, int x, int y, int anchor)
例子:
public void paint (Graphics g) {
g.setcolor(255, 255, 255); // 白色
g.fillRect(0, 0, getWidth( ), getHeight( )); // 實心矩形
Image img = Image.createImage("Splash.png"); // 載入圖片
g.drawImage(img, getWidth( ) / 2, getHeight( ) / 2, Graphics.HCENTER | Graphics.VCENTER); // 中央位置
}
若想增加其他遊戲程式設計相關內容,可電郵至網主提出