Android中Bitmap回收问题
阿神
阿神 2017-04-17 17:35:07
0
5
667

使用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) {
            }
阿神
阿神

闭关修行中......

全部回覆(5)
巴扎黑

你可以等GC去回收,當然,像你這樣手動回收是個好習慣。

補答:

會的,如果兩個引用都是同一個對象,那麼你使用recycle時會讓對像中的圖片被清理。不過清理的是物件中的圖片數據,並不是物件本身,所以說mDragBitmap不會為null,但使用mDragBitmap中的圖片數據時會報錯。

你這裡可以進行一次判斷再回收:

if (srcBitmap != mDragBitmap) {  // 内存地址不同,说明不是同一个对象
    srcBitmap.recycle();
}
PHPzhong

如果你確信沒有進一步的操作就可以調用其recycler方法,释放内存;如果后续有getPixels()setPixels()的調用就不要隨意釋放內存,等待GC的回收,否則會拋異常。

PHPzhong

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=null;可以盡快讓gc回收呢?

小葫芦

雷雷

小葫芦

帶現在的主流版本上,Google已经将Bitmap的内存放到堆中去了,这个回收也交给了gc,所以樓主不用考慮這個問題了。內存不夠時就自動回收了。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板