近期项目中,遇到了一个问题。图片资源文件太大,于是把许多小的透明.png图片合成一个透明条,发现省了不少空间。可是在利用MIDP2.0中的API把大图片拆分成小图片时,画出的小图片都不再是透明了,于是开始想办法解决。
source
if(pngmix != null)

...{
for(short i = 0; i < imgArray.length; i++)

...{
imgArray[i] = Image.createImage(32, 32);
Graphics g = imgArray[i].getGraphics();
g.translate(-32 * i, 0);
g.drawImage(pngmix, 0, 0, Graphics.LEFT | Graphics.TOP);
array = new int[imgArray[i].getWidth() *imgArray[i].getWidth()];
imgArray[i].getRGB(array, 0, imgArray[i].getWidth(), 0, 0, 32, 32);
imgArray[i] = Image.createRGBImage(array, 32, 32, true);
array = null;
}
}
后来在别人指点下,才知道createImage(int, int);是默认opaque 的。
有人告知Nokia API中有可以创建默认transparent的图片函数,可是想到为了通用性,放弃使用。
有人告知使用setClip()函数可以实现不拆分原图片,画出各个透明的小图片。
又有人告知setClip()函数效率不高,所以萌生想法利用getRGB()把小图片画出。
看了下J2ME API,写出如下代码,实现此功能。
source


/** *//**
* @author RollmowN
* @description reate transparent image array from a large size image
* @param Image src
* @param thumbWidth thumbnail image width
* @param thumbHeight thumbnail image height
* @return Image[]
* */
public Image[] createTransparentImageArray(Image src, int thumbWidth,
int thumbHeight)

...{
int size = 0;
int width = src.getWidth();
int height = src.getHeight();
if((width % thumbWidth) != 0)
return null;
size = src.getWidth() / thumbWidth;
Image[] img = new Image[size];
int[] array = new int[width * height];
int[] temp = new int[thumbWidth * thumbHeight];
src.getRGB(array, 0, width, 0, 0, width, height);
for(int len = 0; len < size; len++)

...{
for(int i = 0; i < thumbHeight; i++)

...{
for(int j = 0 ; j < thumbWidth; j ++)

...{
temp[i * thumbWidth + j]
= array[i * width + j + thumbWidth * len];
}
}
img[len] = Image.createRGBImage(temp, thumbWidth, thumbHeight, true);
}
return img;
}

最后程序的界面效果如图,虽然效果实现了但是还需进一步在真机测试性能。