Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Memory problem in my animation

+11 votes
I am doing an animation of deck cards displayed in a circle.

In the onDraw method, I call canvas.drawBitmap method in a for loop, which means that every time the onDraw method is called, the for loop goes through an ArrayList of cards that have been taken from a deck and stored in this ArrayList and draws all of them.

The problem is that the animation starts to get slower as the number of cards in the ArrayList reaches about half of the deck.

Is there any way to display a card, and leave it in the canvas? In other words, is there a way to make the onDraw method only draw the new cards that are added to the ArrayList without going through the whole ArrayList again every time it draws the new card?
asked May 8, 2015 in Spring 2015 by Abdul Rahman Merhi (100 points)
Can you post some of the code where the drawing is being done?
for (int i = 0; i < cardsDisplayed.size(); i++){
                canvas.drawBitmap(getBitmapFromAsset(cardsDisplayed.get(i)),(float) cardsDisplayed.get(i).getX(), (float) cardsDisplayed.get(i).getY(), p);

2 Answers

+4 votes
The approach that I pushed Jayce toward (in person) was actually to cache the individual Bitmap objects (using a HashMap that maps Strings to Bitmap objects.)

The slowness problem wasn't caused by a lack of memory, but rather caused by loading the individual Bitmap images from disk and resizing them every time the draw method was called...
answered May 8, 2015 by Forrest Stonedahl (3,438 points)
I think that if you do the scaling once and save the bitmap scaled down at the beginning that can save some time. Also, there is a rotate method I believe you can use on the bitmaps.
+2 votes

My first thought is to save the canvas as a bitmap after each step. Then when drawing you could draw the saved bitmap and then draw what is new, then save overwrite the saved bitmap. This should limit the draw step to two draws every time.


    public Bitmap getBitmap()
        //this.measure(100, 100);
        //this.layout(0, 0, 100, 100);
       Bitmap bmp = Bitmap.createBitmap(this.getDrawingCache());   
answered May 8, 2015 by Ethan Wojcinski (100 points)