2014-03-06 26 views
0

在我的遊戲的可繪製對象類中,存在一個成員變量,它存儲我在構造函數中分配的位圖,在渲染函數被調用時,位圖變爲null,似乎找出原因。Android位圖變爲空

構造:在

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語句被調用時,空位圖被調用的時間和應用程序崩潰

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); 
    } 

功能。

bmp在構造函數和此函數之間沒有被編輯或使用,並且在第一次調用該函數時,它是空的。

任何幫助非常感謝,謝謝。

回答

3

罪魁禍首是

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

要覆蓋BMP聲明,這是產生命名爲BMP局部變量,不會指定給類變量。您應該將其更改爲

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

希望這會有所幫助。

+0

非常感謝你,我有一種感覺,就像我之前工作過的那樣簡單。 – frasertmay

+0

歡迎您。玩得開心:) – Sanjeev

+0

我也看到了。在IDE中應該是一個警告。 – danny117