Android Bitmap变为null

时间:2014-03-06 17:35:05

标签: java android opengl-es

在我的游戏的drawable对象类中,有一个成员变量存储我在构造函数中指定的位图,到调用render函数时,位图变为null并且我似乎无法工作为什么。

构造

public class AyfaDrawableObject {
    private int mFileLocation;
    private final int mId;
    private Context mContext;
    private Bitmap bmp;

    private int X;
    private int Y;
    private int W;
    private int H;

    public static List<AyfaDrawableObject> ObjectList = new ArrayList<AyfaDrawableObject>();

    public AyfaDrawableObject(int fileloc, Context con) {
        mFileLocation = fileloc;
        mId = ObjectList.size();
        mContext = con;

        ObjectList.add(this);

        Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), mFileLocation);
        //Store width and height
        W = bmp.getWidth();
        H = bmp.getHeight();

        Log.d("DrawableObject", "Width: "+W+" Height: "+H);
        Log.d("DrawableObject", "Object Added to list, ID: "+mId);
        Log.d("DrawableObject", "ID: " + mId + " Filelocation: " + mFileLocation);
    }

中发生错误的功能
public void SetupImage(Context mContext)
{
    // Create our UV coordinates.
    float[] uvs = new float[] {
            0.0f, 0.0f,
            0.0f, 1.0f,
            1.0f, 1.0f,
            1.0f, 0.0f
    };

    // The texture buffer
    ByteBuffer bb = ByteBuffer.allocateDirect(uvs.length * 4);
    bb.order(ByteOrder.nativeOrder());
    uvBuffer = bb.asFloatBuffer();
    uvBuffer.put(uvs);
    uvBuffer.position(0);

    // Generate Textures, if more needed, alter these numbers.
    int[] texturenames = new int[1];
    GLES20.glGenTextures(1, texturenames, 0);

    // Bind texture to texture name
    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texturenames[0]);

    // Set filtering
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);

    if(bmp == null){
        Log.d("DrawableObject","NULL BITMAP");
    }else{
        Log.d("DrawableObject","NON NULL");
    }

    // Load the bitmap into the bound texture.
    GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bmp, 0);
}

当调用if语句时,将调用NULL BITMAP并且应用程序崩溃。

bmp在构造函数和此函数之间没有被编辑或使用,并且第一次调用函数时,它是null。

非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:3)

罪魁祸首

        Bitmap bmp =      BitmapFactory.decodeResource(mContext.getResources(), mFileLocation);

你重写了bmp声明,这导致了一个名为bmp的局部变量,并且不会分配给你的类变量。你应该把它改成

        bmp = BitmapFactory.decodeResource(mContext.getResources(), mFileLocation);

希望这有帮助。