LibGdx中使用非2的N次幂尺寸的图片

48 篇文章 0 订阅
2 篇文章 0 订阅

Libgdx关于载入图片规格的问题

  对于libgdx来说,对载入的图片要求是:宽高都必须是2的N次幂的图片才行,否则会提示:texture width and height must be powers of two。


那么,如何使用非2的N次幂尺寸的图片呢,使用以下函数:


import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;

// 如工程目录assets/texture/001.png下: filePath = "texture/001.png"

/** 载入任意尺寸的图像,创建Texture */
public static Texture loadTexture(String filePath)
{
	Pixmap pic = new Pixmap(Gdx.files.internal(filePath));
	pic = Format2power(pic);	// 图像尺寸转化为2的幂
	return new Texture(pic);	// 从Pixmap构建Texture
}

/** 将Pic转化为尺寸为2的幂的图像 */
public static Pixmap Format2power(Pixmap Pic)
{
	
	int width = Pic.getWidth(), height = Pic.getHeight();	// 获取图像的尺寸
	
	Pixmap image = new Pixmap(closestTwoPower(width), closestTwoPower(height), Format.RGBA8888);
	if (image.getWidth() == width && image.getHeight() == height) return image;	// 若原图像尺寸为2的幂,则直接返回原图像
		
	int color;
	for (int i = 0; i < width; i++)
	{
		for (int j = 0; j < height; j++)
		{
			color = Pic.getPixel(i, j);		// 原图像像素信息
			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;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值