问题描述
我似乎无法想出解决办法。我有2个Java类,具有不同特点,每个调用BitmapFactory.de codeResource得到相同的图像资源,一个,而另一个返回null返回位图。这两个类都在同一个包。
I can't seem to figure this out. I have 2 java classes with different characteristics, each calling BitmapFactory.decodeResource to get the same image resource, one returns the bitmap while the other returns null. Both classes are in the same package.
下面是工程类,它调用BitmapFactory.de codeResource返回位图。我只包括了相关code。
Here is the class that works, it calls BitmapFactory.decodeResource which returns the bitmap. I've only included relevant code.
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);
}
}
下面是不起作用的类。 BitmapFactory.de codeResource在调试返回NULL。我只包含code我觉得是相关的。
Here is the class that doesn't work. BitmapFactory.decodeResource returns a NULL in debug. I've only included code i felt was relevant.
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");
}
}
任何线索任何人吗?
Any clue anyone?
推荐答案
的 getResources()
是上下文
类方法和你不使用你的段类的上下文。它是如何工作的。你应该叫 getApplicationContext()。getResources()
The getResources()
is a Context
class method and you are not using a context in your Segment class. How does it work. You should call getApplicationContext().getResources()
您应该通过上下文的段
构造。
You should pass the context to the Segment
constructor.
public Segment(Context context, int x, int y) {
....
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.droid_1);
....
}
这篇关于安卓:BitmapFactory.de codeResource返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!