Android从资源加载调整大小的图像



我在android游戏中获得内存错误,我认为这是由我的图像加载功能引起的。我的手机上一切正常,但在平板电脑上,我得到内存超过错误。

我正在使用矩阵,因为我需要将图像大小调整为浮点值。但是在这种情况下,我必须首先加载全尺寸的图像,然后用矩阵调整它的大小,我认为这会导致内存错误。

这是正确的方式来处理图像的大小?

public class Sprite {
    private Bitmap bitmap = null;
    private float scaleX, scaleY;
    public Sprite(String path, float targetWidth, float targetHeight, Context context) {
        InputStream istr;
        AssetManager assetManager = context.getAssets();
        Matrix scalematrix = new Matrix();
        try {
            istr = assetManager.open(path);
            bitmap = BitmapFactory.decodeStream(istr);
            scaleX = targetWidth / bitmap.getWidth();
            scaleY = targetHeight / bitmap.getHeight();
            scalematrix.postScale(scaleX, scaleY);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), scalematrix, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
}

BitmapFactory。选项有public int inSampleSize——如果设置值> 1,请求解码器对原始图像进行子采样,返回一个较小的图像以节省内存。

您可以尝试使用BitmapFactory.decodeXXX(..., BitmapFactory.Options opts) (decodeFile()等)

最新更新