开发者

Crossfading between 3 images in a UIButton, on iOS

I am trying to implement a clickable image that is able to repeatedly cycle through three or more images. I don't need to interact with the images once the cycle is set up. The cycling is time based, rather than event based. The images should smoothly transition from one to another.

Wha开发者_Python百科t is the best way to approach this problem?

My first approach was a finite state machine in a single method, and chain UIView animation blocks together using a selector of that method. This failed as [button setImage:nextImage forState:UIControlStateNormal] is not animated.

My second approach was to look at CABasicAnimation and layers. This seemed to be a more low level approach, but I couldn't see a way of chaining the transitions together (e.g. setting a next action once this action was complete).

My gut feeling that approaches using multiple buttons and fading between them is plain wrong, but am not sure where to go next.

How do I smoothly fade between images in a UIButton?

How do I chain those transitions together?

What is the right way?

Edit: The images i1, i2, i3 need to go in sequence i1 -> i2 -> i3 -> i2 -> i1 -> i2 -> i3 etc


My first thought is UIImageView.animationImages, but I don't think it supports fading.

Don't use a UIButton to display the image; just make it an invisible button on top of something else that handles the drawing.

One of the easy ways to do the animation you want is to use two image views: Move the "fading in" image view to the front (-[UIView bringSubviewToFront:]) set its alpha to 0, and then animate its alpha to 1.


My solution:

  • Have a UIButton and a container UIView.
  • The container UIView contained all the images as UIImageView child views.
  • Kick off the animation in the UIViewController's viewDidAppear method, where all child views had there alpha set to 1.0. Then set the 0th imageView alpha to 1.0.
  • When this animation is finished, recall the same method, which sets a delay
  • and takes care of animating to the next image.

I'm not sure if it's correct way of doing things, but it seemed a lot neater than the alternative -

  • all the images could be set up in Interface Builder without any pollution of the image names in the code.
  • the method was self contained, and memory management hassle free.


I'm fairly sure that something like this will work:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];

[button setImage:whicheverImage forState:UIControlStateNormal];

[UIView commitAnimations];

It should fade through smoothly if you give it a duration of maybe 0.5 (seconds).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜