遇到的问题
先贴问题代码:
public void setmBitmap(String path){
mBitmap = BitmapFactory.decodeFile(path); //这里有错
mCanvas.setBitmap(mBitmap);
invalidate();
}
就是这段小小的代码,让我调试了两个钟头,(哭...
分析
调试一下就会发现问题,直接上图:
image.png
有一个Bitmap.isMutable()方法,那这个方法代表着什么呢?
官方给的解释:
Returns true if the bitmap is marked as mutable (i.e. can be drawn into)
返回这个Bitmap是否可以被绘制。
也就是说Bitmap里面一个boolean的变量,标志着是否能够绘制该Bitmap。
简单查看一下源码就能得到一个变量:
private final boolean mIsMutable;
也就是说,通过BitmapFactory.decodeFile()方法得到的bitmap是一个无法被绘制的。
问题已经找出来了,那就自然而然的能解决啦!
解决
既然是因为bitmap的内部字段mIsMutable为false导致的,那我们就改变一下这个变量的值,让它变为true。
通过查询,使用Bitmap.copy()方法
image.png
这个方法返回一个新的Bitmap,只需要把第二个参数设置为true:
mBitmap = BitmapFactory.decodeFile(path).copy(Bitmap.Config.ARGB_8888, true);
问题就解决啦