我使用此方法,如果文件是 xml,它每次都有效,如果它是任何其他格式,则失败。
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId);
下面将工作,因为它有 xml,
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
drawable 文件夹中有 test.PNG 图片,但无法正常工作:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.test);
what is missing in this code to support decoding other format?
I am not specifically scaling the bitmap on test image and it is small too.
这是日志:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ram.myapplication, PID: 12759
java.lang.NullPointerException
at android.graphics.Canvas.throwIfCannotDraw(Canvas.java:1083)
at android.graphics.Canvas.drawBitmap(Canvas.java:1139)
at com.example.ram.myapplication.MySurfaceView.drawSomething(MySurfaceView.java:96)
at com.example.ram.myapplication.MySurfaceView$1.surfaceCreated(MySurfaceView.java:69)
at android.view.SurfaceView.updateWindow(SurfaceView.java:608)
at android.view.SurfaceView.access$000(SurfaceView.java:96)
at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:185)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:847)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1994)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1063)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5993)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
非常感谢您的宝贵时间。
编辑: 我不得不更改目录。在某处找到 - 无法使用 Drawable 文件夹。所以不得不使用原始文件夹。
最佳答案
使用BitmapFactory.Options
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.test, options);
if options.inJustDecodeBounds = false;
如果设置为 true,解码器将返回 null(无位图),但 out... 字段仍将被设置,允许调用者查询位图而无需为其像素分配内存。
希望它能奏效!!
关于Android:BitmapFactory.decodeResource(r,id) - 显示 NPE 以从可绘制对象解码图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48071283/