使用Bitmap的静态方法createScaledBitmap来创建一个符合规格的Bitmap的时候,原生的bitmap是否需要回收?
代码如下:
private void initDragBitmap() {
Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.mingren);
mDragBitmap = Bitmap.createScaledBitmap(srcBitmap, FLOAT_BALL_WIDTH, FLOAT_BALL_HEIGHT, true);
srcBitmap.recycle();
}
代码中srcBitmap是否需要回收?
补充问题:
看了大家的回复,基本可以确定如果srcBitmap后续不再使用了,确实是可以手动recycle的,同时它本身也是个局部变量,是可以等待系统GC的。
那新问题来了(或者说我最初想问的问题来了),当createScaledBitmap方法中传入的宽和高跟srcBitmap相同时,通过createScaledBitmap代码注释可以看出它是将srcBitmap返回了,这个时候我强行recycle了srcBitmap,会不会导致mDragBitmap也为null?
源码注释:
/**
* Creates a new bitmap, scaled from an existing bitmap, when possible. If the
* specified width and height are the same as the current width and height of
* the source bitmap, the source bitmap is returned and no new bitmap is
* created.
*
* @param src The source bitmap.
* @param dstWidth The new bitmap's desired width.
* @param dstHeight The new bitmap's desired height.
* @param filter true if the source should be filtered.
* @return The new scaled bitmap or the source bitmap if no scaling is required.
* @throws IllegalArgumentException if width is <= 0, or height is <= 0
*/
public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight,
boolean filter) {
}
You can wait for the GC to recycle. Of course, it is a good habit to recycle manually like you do.
Answer:
Yes, if the two references are the same object, then when you use recycle, the images in the object will be cleaned. However, what is cleaned is the image data in the object, not the object itself, so mDragBitmap will not be null, but an error will be reported when using the image data in mDragBitmap.
You can make a judgment and then recycle it here:
If you are sure that there is no further operation to call its
recycler
方法,释放内存;如果后续有getPixels()
与setPixels()
call, do not release the memory at will and wait for GC recycling, otherwise an exception will be thrown.private void initDragBitmap() {
}
Regarding the above code, I would like to discuss a question with you. Is it possible to use srcBitmap=null; can the gc be recycled as soon as possible?
is brought to the current mainstream version,
Google
已经将Bitmap
的内存放到堆中去了,这个回收也交给了gc
, so the author does not need to consider this issue. When the memory is not enough, it is automatically recycled.