IllegalStateException while adding bitmap to Canvas
I was trying to set a bitmap image to a canvas using setBitMap
,at that time I got an IllegalStateException.This canvas have some images on it currently, I am trying to replace it.
Any one have any idea why this happened?
Code Snippet
editBm = Bitmap.createBitmap(951, 552, Bitmap.Config.ARGB_8888);
Canvas mCanvas=new Canvas(editBm);
eBit=LoadBMPsdcard(filePath); ---->returns a bitmap when the file path to the file is provided
Log.i("BM size", editBm.getWidth()+"");
mCanvas.setBitmap(eBit);
I am not getting any NullPointer errors and the method LoadBMPsdcard()
is working good.
Please 开发者_StackOverflowlet me know about any ideas you have ...
Thanks in advance
Happy Coding
IllegalStateException could be thrown because you're loading a Bitmap (eBit) and use mCanvas.setBitmap(eBit)
without checking if the bitmap is mutable. This is requiered to draw on the Bitmap. To make sure your Bitmap is mutable use:
eBit=LoadBMPsdcard(filePath);
Bitmap bitmap = eBit.copy(Bitmap.Config.ARGB_8888, true);
canvas.setBitmap(bitmap);
Try to use drawBitmap instead of the setBitmap. It looks like you've already set a bitmap to draw into by passing it to the canvas constructor, so now you just need to draw everything onto it.
Canvas.setBitmap()
throws IllegalStateException
if and only if Bitmap.isMutable()
returns true. Bitmap.createBitmap()
builds an immutable Bitmap instance only, in all of its forms. To create a mutable bitmap you either use new Bitmap()
, or Bitmap.copy(true)
, depending on whether you have a source bitmap that you want to start with. A typical block for me looks like:
Bitmap image = ...
Canvas c = new Canvas(image.isMutable()?image:image.copy(true));
...
This assumes, of course, that you don't mind clobbering the source Bitmap (which I generally don't but that's by no means universal).
精彩评论