gpt4 book ai didi

android - 如何从android的默认资源中获取位图?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:58:53 25 4
gpt4 key购买 nike

你好我是用这种方式做的

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

如果您确定它是位图,将可绘制对象转换为 BitmapDrawable 并从那里获取位图:

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

位图也可能为空。

关于android - 如何从android的默认资源中获取位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14833268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com