如何从android的默认资源中获取Bitmap?

时间:2013-02-12 13:05:42

标签: android bitmap

嗨,我正是这样做的

Bitmap bm = BitmapFactory.decodeResource(getResources(), android.R.drawable.list_selector_background);

int c = bm.getPixel(bm.getWidth()/2, bm.getHeight()/2);

但是bm是null,在第二行给出了NullPointerException

错误:

02-12 18:29:57.568: E/AndroidRuntime(5086):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at android.os.Looper.loop(Looper.java:137)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at android.app.ActivityThread.main(ActivityThread.java:4424)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at java.lang.reflect.Method.invokeNative(Native Method)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at java.lang.reflect.Method.invoke(Method.java:511)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at dalvik.system.NativeStart.main(Native Method)
02-12 18:29:57.568: E/AndroidRuntime(5086): Caused by: java.lang.NullPointerException
02-12 18:29:57.568: E/AndroidRuntime(5086):     at com.example.showhide.MainActivity.onCreate(MainActivity.java:38)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at android.app.Activity.performCreate(Activity.java:4465)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
02-12 18:29:57.568: E/AndroidRuntime(5086):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)

3 个答案:

答案 0 :(得分:6)

这是因为此资源是StateListDrawable,而不是Bitmap。你应该使用:

 Drawable d = getResources().getDrawable(android.R.drawable.list_selector_background);

如果您确定它是位图,请将drawable转换为BitmapDrawable并从那里获取位图:

Drawable currentState = d.getCurrent();
if(currentState instanceof BitmapDrawable)
    Bitmap b = ((BitmapDrawable)currentState).getBitmap();

位图也可以为空。

答案 1 :(得分:4)

您应该使用Resources.getSystem()代替getResources

Bitmap bm = BitmapFactory.decodeResource(Resources.getSystem(), android.R.drawable.list_selector_background);

因为您尝试访问的资源不在您自己的资源中,而是在系统中。

编辑:

在错误的资源旁边,您正在尝试从作为选择器的资源(xml文件)获取drawable。请获得正确的drawable资源:) http://androidxref.com/4.1.1/xref/frameworks/base/core/res/res/drawable/list_selector_background.xml

答案 2 :(得分:4)

不使用BitmapFactory:

Bitmap bmp = ((BitmapDrawable) context.getResources()
             .getDrawable(R.drawable.list_selector_background)).getBitmap();