本文介紹如何在程序運行時將一個較大的圖片分割為Image數組。實現此功能最重要的就是使用Graphics的坐標變換和繪制圖片的功能。也就是使用translate()和drawImage()方法。
我們設計一個ImageUtil類,如下所示:
/**
* Copyright_2006, eric zhan
* Created on 2006-6-8
*/
package com.j2medev.image;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
public class ImageUtil {
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;
}
}
靜態方法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來看看效果,代碼如下:
/**
* Copyright_2006, eric zhan
* Created on 2006-6-8
*/
package com.j2medev.image;
import java.io.IOException;
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;
public class ImageMIDlet extends MIDlet {
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
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));
}
}
class ImageCanvas extends Canvas {
private Image img = null;
public ImageCanvas(Image _img) {
this.img = _img;
}
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);
}
}
}
}
}
}
准備一個圖片test.png,即可運行。我們建議圖片的高度應該和行數成正比,圖片的寬度與列數成正比。為了顯示出分割的效果,這裡把小圖片之間加了一點間距。