在工作里面发现即使对于我们常常使用的Image对象,我们很多时候还是缺乏深刻了解的。
一般我们使用图片的时候会按照如下的操作:
Image s_image = Image.createImage(SCREEN_W, SCREEN_H);
Graphics s_g = s_image.getGraphics();
有时候就会遇见一些bug,比如无法获取s_g,明明自己调用了Image的getGraphics()方法的。
其实,主要的原因在于:
Image 分为可变图片和不可变图片,而任何从资源创建的都是不可变图片,任何使用了图片data数据在create的图片都是不可变的。
在API里面只有一种方法可以创建可变图片。即:
Image s_image = Image.createImage(SCREEN_W, SCREEN_H);
附上API里面的Image创建方法吧:
static Image | createImage(byte[] imageData, int imageOffset, int imageLength) |
static Image | createImage(Image source) |
static Image | createImage(Image image, int x, int y, int width, int height, int transform) |
static Image | createImage(InputStream stream) |
static Image | createImage(int width, int height) |
static Image | createImage(String name) |
static Image | createRGBImage(int[] rgb, int width, int height, boolean processAlpha) |
对了,API里面提供了一种方法来检测Image 图片是否为可变图片
isMutable()
所以在容易出错的地方,我们在获取G的时候可以用如下的代码增强健壮性:
Graphics s_g;
if ( s_image.isMutable())
{
s_g = s_image.getGraphics();
}