Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

animation - Create animated splash screen using frames on Android

So here's the deal, I've searched every single question and link online but none are helpful. I have 120 frames of an animation in .jpg format for my splash screen. I understand that jpegs are converted to bitmaps on memory so that's why I get an OutOfMemoryError. The maximum frames I get to animate are 10. Is there any way to do this frame by frame, or should I try something else. Here's my code:

    final AnimationDrawable anim = new AnimationDrawable();
    anim.setOneShot(true);

    for (int i = 1; i <= 120; i++) 
    {
        Drawable logo = getResources().getDrawable(getResources()
                  .getIdentifier("l"+i, "drawable", getPackageName()));

        anim.addFrame(logo, 50);
        if (i % 3 == 0)
        {
            System.gc();
        }
    }

    ImageView myImageView = (ImageView) findViewById(R.id.SplashImageView);
    myImageView.setBackgroundDrawable(anim);
    myImageView.post(new Runnable()
    {
       public void run()
       {
          anim.start();
       }
    });

I've placed the 120 jpegs under the drawable folder with an "l" prefix (eg l1, l2 etc). I do garbage collection every 3 jpegs but that won't do a thing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try to do it without AnimationDrawable using Handler.postDelayed. Something like this:

final ImageView image = (ImageView) findViewById(R.id.SplashImageView);
final Handler handler = new Handler();

final Runnable animation = new Runnable() {
    private static final int MAX = 120;
    private static final int DELAY = 50;

    private int current = 0;

    @Override
    public void run() {
        final Resources resources = getResources();
        final int id = resources.getIdentifier("l" + current, "drawable", getPackageName());
        final Drawable drawable = resources.getDrawable(id);

        image.setBackgroundDrawable(drawable);
        handler.postDelayed(this, DELAY);
        current = (current + 1) % MAX;
    }
};

handler.post(animation);

This solution requires less memory because it keeps only one drawable at the time.

You can cancel the animation using handler.removeCallbacks(animation);.

If you want make a one-shot animation you can call handler.postDelayed conditionally:

if (current != MAX - 1) {
    handler.postDelayed(this, DELAY);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...