Android中Bitmap回收问题

查看:1004
本文介绍了Android中Bitmap回收问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

解决方案

你可以等待GC去回收,当然,像你这样手动回收是个好习惯。

补答:

会的,如果两个引用都是同一个对象,那么你使用recycle时会让对象中的图片被清理。不过清理的是对象中的图片数据,并不是对象本身,所以说mDragBitmap不会为null,但是使用mDragBitmap中的图片数据时会报错。

你这里可以进行进行一次判断再回收:

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

这篇关于Android中Bitmap回收问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆