Search code examples
android-animationandroid-drawablexml-drawable

Efficient way to load large image sequences for animation


I have 4 image sequences (png format) that I need to use for my animations. Each sequence is about 50 frames long and each frame is about 300x300, so I have something like 30 MB of resources to load. What's the most efficient way to load them to avoid memory leaks? Should I go for xml drawable animations or there's a better way?

I don't need to display all of them on the screen at the same time. Only one animation at time will be displayed.


Solution

  • Maybe is a bit late :) but I hope this can help other users. At the end I've solved it with a simple loop which loads an image, draws it and destroy it.

            int frames = 50;
    
            //LOADING-REMOVING NEEDED FRAMES
            //set animation range
            i = currentFrame % frames;
            //frame to cache
            frameList.add(BitmapsLoader(i)); //custom function to load a specified frame from res
            if (frameList.size() == 3) {
                //frame to draw
                canvas.drawBitmap(frameList.get(1), left, top, null);
                //frame to remove
                frameList.get(0).recycle();
                frameList.remove(0);
            }
    

    This keeps the memory allocation stable, no matters how many frames your animation is. Obviously it costs more on CPU, as we're not pre-loading all resources but we keep loading them at each frame. Despite these facts, my app is running smoothly. Tested on a Samsung Galaxy S3 and on a Galaxy Tab 4.