在游戏开发中,包的大小总是与图片资源的大小密切相关,而图片资源中,大多为带有透明度信息的png图像。
那么,如何精简png图片资源呢?
1、图像压缩是一种方法,然而随着压缩率的增大、图片品质也越来越差。(舍弃)
2、我们另辟蹊径,采用png图像拆分。(近乎无损,资源精简)
1、LibGdx中,通过Pixmap使用
// 如工程目录assets/texture/0_1.jpeg下:
/** 从工程资源路径下获取图像,如:filePath1 = "texture/0_1.jpeg"、filePath2 = "texture/0_2.jpeg" */
public static Texture getTexture(String filePath1, String filePath2)
{
try
{
Pixmap pic1 = new Pixmap(Gdx.files.internal(filePath1));
Pixmap pic2 = new Pixmap(Gdx.files.internal(filePath2));
Pixmap pic = Combine(pic1, pic2); // 合并为png图像
return new Texture(pic); // 创建Texture
}
catch (Exception ex)
{
return null;
}
}
/** 从Pic和Mask合成图像 */
public static Pixmap Combine(Pixmap Pic, Pixmap Mask)
{
int width = Pic.getWidth(), height = Pic.getHeight(); // 获取图像的尺寸
Pixmap image = new Pixmap(closestTwoPower(width), closestTwoPower(height), Format.RGBA8888); // 合成尺寸为2的幂
int color1, color2, color, alpha;
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
color1 = Pic.getPixel(i, j); // 原图像像素信息
color2 = Mask.getPixel(i, j); // 原图像透明度信息
alpha = (color2 & 0xff00) >> 8; // 透明度
color = alpha == 0 ? 0 : (color1 & 0xffffff00) | alpha; // 合成像素点
image.drawPixel(i, j, color); // 生成图像
}
}
return image;
}
/** 获取最接近于n的2的幂 */
public static int closestTwoPower(int n)
{
int power = 1;
while (power < n)
power <<= 1;
return power;
}
/** 从工程资源路径下获取图像,如:filePath1 = "0_1.jpeg"、filePath2 = "0_2.jpeg" */
public static Bitmap getBitmap(String pathName1, String pathName2)
{
try
{
Bitmap pic1 = BitmapFactory.decodeFile(pathName1);
Bitmap pic2 = BitmapFactory.decodeFile(pathName2);
Bitmap pic = Combine(pic1, pic2); // 合并为png图像
return pic;
}
catch (Exception ex)
{
return null;
}
}
/** 从Pic和Mask创建bitmap图像 */
public static Bitmap Combine(Bitmap Pic, Bitmap Mask)
{
int width = Pic.getWidth(), height = Pic.getHeight(); // 获取图像的尺寸
Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int color1, color2, color;
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
color1 = Pic.getPixel(i, j); // 原图像像素信息
color2 = Pic.getPixel(i, j); // 原图像透明度信息
color = (color1 & 0x00ffffff) | ((color2 & 0x00ff0000) << 8); // 合成像素点
image.setPixel(i, j, color); // 生成图像
}
}
return image;
}
原文地址:http://blog.csdn.net/scimence/article/details/45847661