Reputation: 578
I'd like to build a nice background to a view with images fading out & in. BUT, I also would like the animation not to stop.
I was already using this :
backgroundUIImageView.animationImages =
[UIImage(named:"testimage1"), UIImage(named:"testimage2")]
backgroundUIImageView.animationDuration = 10
backgroundUIImageView.animationRepeatCount = 0
backgroundUIImageView.startAnimating()
Problem : The transitions are not faded
I also tried this :
var UIImage1=UIImage(named:"testimage1")
var UIImage2=UIImage(named:"testimage2")
var crossFade = CABasicAnimation(keyPath:"contents")
crossFade.duration = 5.0
crossFade.fromValue = UIImage1.CGImage
crossFade.toValue = UIImage2.CGImage
self.backgroundUIImageView.layer.addAnimation(crossFade, forKey:"animateContents")
self.backgroundUIImageView.image = UIImage2
problem : the animation is not repeated and the code is really ugly & unsafe in my opinion..
Would anyone have any idea/code example about how to do this ?
Upvotes: 1
Views: 1368
Reputation: 514
i just needed to do this myself. I used a combination of NSTimer and CA crossfade. Every time your timer fires you get a nice fade transition. Adjust the length of the animation and the timer interval to set the pace of your animation.
func startAnimatingLoadingImage() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target:self, selector: Selector("flipImage"), userInfo: nil, repeats: true)
}
and this
func flipImage() {
let cell1 = UIImage(named: "dots1")!
let cell2 = UIImage(named: "dots2")!
let cell3 = UIImage(named: "dots3")!
let cell4 = UIImage(named: "dots4")!
let cells = [cell1, cell2, cell3, cell4]
let numCells = cells.count - 1
let currentImage = cells[currentCell]
var nextImage: UIImage
if currentCell == numCells {
nextImage = cells[0]
self.currentCell = 0
} else {
let x = currentCell + 1
nextImage = cells[x]
self.currentCell = x
}
let crossFade = CABasicAnimation(keyPath:"contents")
crossFade.duration = 0.25
crossFade.fromValue = currentImage.CGImage
crossFade.toValue = nextImage.CGImage
self.loadingView.layer.addAnimation(crossFade, forKey:"animateContents")
self.loadingView.image = nextImage
}
Upvotes: 1
Reputation: 26383
I don't know how to write it in SWIFT, but I use this snippet.
To repeat you should add the options UIViewAnimationOptionAutoreverse
and UIViewAnimationOptionRepeat
UIImage * toImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
[UIView transitionWithView:self.imageView
duration:0.8f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.imageView.image = toImage;
} completion:nil];
Upvotes: 3