如何保持在内存中的位图 [英] How to keep a Bitmap in memory

查看:152
本文介绍了如何保持在内存中的位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在<一个跟进href=\"http://stackoverflow.com/questions/8814455/storing-a-bitmap-resource-in-a-static-variable\">Storing在一个静态变量一个位图资源,似乎存储在查看静态引用到 android.graphics.Bitmap 可能会泄漏到第一个查看的实例吧。是什么在Android的解决这一惯用方法是什么?我不想叫 BitmapFactory.de codeResource(资源ID)每个这种观点的一个实例的实例,因为这将在完成(很多次)时间每一个活动。我想这个小位图来始终保持在内存中。那么,什么是做如下正确的方法:

 公共类MyView的扩展视图{
    私有静态位图星;
    公共MyView的(上下文的背景下){
        同步(本){
            如果(星== NULL){
                明星= BitmapFactory.de codeResource(getResources(),R.drawable.star);
            }
        }
    }
    // ...
}


解决方案

创建您查看静态的清理方法,你从你的活动称之为的onPause ()。在调用,调用位图的循环()并清除参考。同样的,而不是建立在构造函数中的位图,有一个初始化调用您在打电话给你活动的 onResume()

如果您有任何担心,因为你的看​​法是整个活动中可能存在的重叠,你可以有init和清理通话保持一个引用计数,这样,当计数命中0位图不仅破坏。如果位图足够小,可以考虑的onCreate() / 的onDestroy()以及

请务必在空您的视图类使用它之前检查的位图的参考。

Following up on Storing a Bitmap resource in a static variable, it seems that storing a static reference to an android.graphics.Bitmap in a View may leak a reference to that first View that instantiated it. What's the idiomatic way to solve this in Android? I do not want to call BitmapFactory.decodeResource(resource, id) each time an instance of this view is instantiated because this will be done (many times) in every single Activity. I want this small Bitmap to always remain in memory. So, what is the correct way to do the following:

public class MyView extends View {
    private static Bitmap star;
    public MyView(Context context) {
        synchronized(this) {
            if (star == null) {
                star = BitmapFactory.decodeResource(getResources(), R.drawable.star);
            }
        }
    }
    // ...
}

解决方案

Create a static clean-up method in your View that you call from your Activity's onPause(). In that call, call the bitmap's recycle() and clear out the reference. Likewise, instead of creating the bitmap in the constructor, have an initialization call that you call in your activity's onResume().

If you have any concerns that there might be an overlap because your View is used across activities, you can have the init and clean-up calls maintain a reference count, so that the bitmap is only destroyed when the count hits 0. If the bitmap is small enough, you can consider onCreate()/onDestroy() as well.

Be sure to check the bitmap reference in your view class for null before using it.

这篇关于如何保持在内存中的位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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