本文介绍如何在程序运行时将一个较大的图片分割为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,即可运行。我们建议图片的高度应该和行数成正比,图片的宽度与列数成正比。为了显示出分割的效果,这里把小图片之间加了一点间距。