Android:BitmapFactory.decodeResource返回null

Kev*_*vin 12 graphics android bitmap android-context

我似乎无法弄清楚这一点.我有2个具有不同特征的java类,每个类调用BitmapFactory.decodeResource来获取相同的图像资源,一个返回位图而另一个返回null.两个类都在同一个包中.

这是有效的类,它调用BitmapFactory.decodeResource返回位图.我只包含相关代码.

package advoworks.test;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainScreen extends SurfaceView implements SurfaceHolder.Callback {

    private static final String TAG = MainScreen.class.getSimpleName();

    public MainScreen(Context context) {
        super(context);

        Bitmap bitmap;
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.droid_1);

        //adding the callback (this) to the surface holder to intercept events;
        getHolder().addCallback(this);

        // make the GamePanel focusable so it can handle events
        setFocusable(true);

    }
}
Run Code Online (Sandbox Code Playgroud)

这是不起作用的类.BitmapFactory.decodeResource在调试中返回NULL.我只包括我觉得相关的代码.

package advoworks.test;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.Log;

public class Segment {

    private int x;
    private int y;
    private Bitmap bitmap;

    public Segment(int x, int y) {
        Log.d(TAG, "Creating Segment");
        try {
            this.bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.droid_1);
        } catch (Exception e) {
            Log.d(TAG,"Error is " + e);
        }   
        this.x = x;
        this.y = y;
        Log.d(TAG, "Created Segment");
    }
}
Run Code Online (Sandbox Code Playgroud)

有人知道吗?

Eli*_*Eli 6

检查图像的分辨率,如果它太大,BitmapFactory.decodeResource将只返回null(无异常)


Ron*_*nie 4

getResources()是一个Context类方法,您没有在 Segment 类中使用上下文。它是如何工作的。你应该打电话getApplicationContext().getResources()

您应该将上下文传递给Segment构造函数。

public Segment(Context context, int x, int y) {
    ....
    bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.droid_1);
    ....
}
Run Code Online (Sandbox Code Playgroud)