[英]android, how to get resource identifier from bitmap/drawable in memory?
[英]How to get Bitmap from android's default resource?
嗨,我正在使用這種方式執行此操作
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)
這是因為這個資源是一個 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();
位圖也可以為空。
您應該使用Resources.getSystem()
而不是getResources
Bitmap bm = BitmapFactory.decodeResource(Resources.getSystem(), android.R.drawable.list_selector_background);
因為您嘗試訪問的資源不在您自己的資源中,而是在系統的資源中。
編輯:
在錯誤的資源旁邊,您正試圖從作為選擇器(xml 文件)的資源中獲取可繪制對象。 請獲取正確的可繪制資源:) http://androidxref.com/4.1.1/xref/frameworks/base/core/res/res/drawable/list_selector_background.xml
不使用 BitmapFactory:
Bitmap bmp = ((BitmapDrawable) context.getResources()
.getDrawable(R.drawable.list_selector_background)).getBitmap();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.