本文先容如何在程序運行時將一個較大的圖片分割為Image數組。實現此功效最重要的就是應用Graphics的坐標變換和繪制圖片的功效。也就是應用translate()和drawImage()方法。
我們設計一個ImageUtil類,如下所示:
<p>/** * Copyright_2006, eric zhan * Created on 2006-6-8 */ package com.J2MEdev.image;</p><p>import Javax.microedition.lcdui.Graphics; import Javax.microedition.lcdui.Image;</p><p>public class ImageUtil {</p><p> public static Image[] splitImage(Image img, int rows, int cols) { if(img == null) return null; Image[] result = new Image[rows * cols]; int w = img.getWidth()/cols; int h = img.getHeight()/rows; for(int i = 0;i<result.length;i++){ result[i] = Image.createImage(w,h); Graphics g = result[i].getGraphics(); g.translate((-i%cols)*w,(-i/cols)*h); g.drawImage(img,0,0,Graphics .LEFT|Graphics.TOP); } return result; }</p><p>}</p>靜態方法splitImage(Image img,int rows,int cols)把參數img指定的Image對象分割為rows行cols列的Image數組。這裡我們把數組存儲為一維數組,當然您也可以存儲為二維數組。根據img的高度和寬度以及目標數組的行數和列數,可以盤算出每個小圖片的高度和寬度,並且每個圖片的高度和寬度應當是相等的。Graphics的 translate(int x,int y)方法可以將graphics高低文的原點變換到(x,y),這樣隨後的繪畫動作都是以新的原點為准了。隨後我們調用drawImage()就可以把 img的部分內容繪畫的新的Image中。循環結束後,把Image數組返回。
下面編寫一個測試的MIDlet來看看後果,代碼如下:
<p>/** * Copyright_2006, eric zhan * Created on 2006-6-8 */ package com.J2MEdev.image;</p><p>import Java.io.IOException;</p><p>import Javax.microedition.lcdui.Canvas; import Javax.microedition.lcdui.Display; import Javax.microedition.lcdui.Form; import Javax.microedition.lcdui.Graphics; import Javax.microedition.lcdui.Image; import Javax.microedition.midlet.MIDlet; import Javax.microedition.midlet.MIDletStateChangeException;</p><p>public class ImageMIDlet extends MIDlet {</p><p> protected void destroyApp(boolean arg0) throws MIDletStateChangeException {</p><p> }</p><p> protected void pauseApp() { // TODO Auto-generated method stub</p><p> }</p><p> protected void startApp() throws MIDletStateChangeException { // TODO Auto-generated method stub Display display = Display.getDisplay(this); Image img = null; try { img = Image.createImage("/test.png"); } catch (IOException ex) { Form form = new Form("error"); form.append("error to load the img"); display.setCurrent(form); return; } display.setCurrent(new ImageCanvas(img));</p><p> }</p><p>}</p><p>class ImageCanvas extends Canvas {</p><p> private Image img = null;</p><p> public ImageCanvas(Image _img) { this.img = _img; }</p><p> public void paint(Graphics g) { int color = g.getColor(); g.setColor(0xFFFFFF); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(color); if (img != null) { // before split g.drawImage(img, 0, 0, Graphics.LEFT | Graphics.TOP); // after int distance = img.getHeight() + 6; Image[] sprites = ImageUtil.splitImage(img, 3, 4); if (sprites != null) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { g.drawImage(sprites[4 * i + j], j * sprites[4 * i + j].getWidth()+2*j, distance + i * sprites[4 * i + j].getHeight()+2*i, Graphics.LEFT | Graphics.TOP); } } } } } }</p>
准備一個圖片test.png,即可運行。我們建議圖片的高度應當和行數成正比,圖片的寬度與列數成正比。為了顯示出分割的後果,這裡把小圖片之間加了一點間距。