Add transition to an AnimationDrawable

2020-02-06 06:18发布

问题:

I have a set of 10 images, and I want to create an animation where I cross fade between them. I've been looking into built-in Drawable to achieve such a thing, but no luck on that part. There is the AnimationDrawable, that switch between pictures, but it doesn't animate the switch. There is the TransitionDrawable, that cross fade between two pictures, but no more than two.

Hell.

I looked for some solution on Google, but no luck on that part. So I'm thinking about implementing my own drawable to achieve such a thing. Would any of you have any pointers ?

Thanks in advance.

回答1:

Not sure if you found an answer to this, but I had the same problem and ended up building my own class based on TransitionDrawable.

Usage:

CyclicTransitionDrawable ctd = new CyclicTransitionDrawable(new Drawable[] { 
  drawable1, 
  drawable2, 
  drawable3, 
  ... 
});

imageView.setImageDrawable(ctd);

ctd.startTransition(1000, 3000) // 1 second transition, 3 second pause between transitions.

The code for the CyclicTransitionDrawable is available on Github.



回答2:

Well. Long time has passed, and you probably fixed the issue, but you got setEnterFaceDuration() for AnimationDrawable. Example:

mBackgroundAnimation = new AnimationDrawable();
mBackgroundAnimation.addFrame(getResources().getDrawable(R.drawable.background1), 5000); 
// ... rest of the frames
mBackgroundAnimation.addFrame(getResources().getDrawable(R.drawable.background6), 5000);
mBackgroundAnimation.setEnterFadeDuration(1000);
mBackgroundAnimation.setOneShot(false);

With this code you have an easy cycling through 1..N images, each one remains 5s (5000ms) with a fade-in animation. Now, what i do is setting the background of my root RelativeLayout

mLayoutRoot.setBackground(mBackgroundAnimation);
mLayoutRoot.post(new AnimationStarterThread());

And the AnimationStarterThread class

private class AnimationStarterThread implements Runnable {
    public void run() {
        if(mBackgroundAnimation != null)
             mBackgroundAnimation.start();
    }
}