Reputation: 3636
I need to implement a random "pulse" animation on an imageview. Random, because I don't want a simple loop animation which repeat it forever each x seconds. The pulsation has to be irregular.
I need a random delay, random duration, and if it's possible random value for fromValue and toValue.
My code for a simple pulse animation, repeat each 5 sec, with an opacity to 0 from 1 :
var pulseAnimation:CABasicAnimation = CABasicAnimation(keyPath: "opacity")
pulseAnimation.duration = 5.0
pulseAnimation.fromValue = NSNumber(float: 0.0)
pulseAnimation.toValue = NSNumber(float: 1.0)
pulseAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
pulseAnimation.autoreverses = true
pulseAnimation.repeatCount = Float.infinity
myimageview.layer.addAnimation(pulseAnimation, forKey: "opacity")
If I write something like :
pulseAnimation.duration = arc4random(....) //I will have a "fixed" random value
How can I do to implement irregular values ?
Upvotes: 0
Views: 1815
Reputation: 3636
Ok I found a method :
for loopNumber in 1...5 {
let myImageView = UIImageView()
myImageView.image = UIImage(named: "nameImageView")
myImageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
self.view.addSubview(myImageView)
var pulseAnimation = CABasicAnimation(keyPath: "opacity")
pulseAnimation.fromValue = Double(arc4random_uniform(6)+1)/10
pulseAnimation.toValue = Double(arc4random_uniform(6)+2)/10
pulseAnimation.duration = Double(loopNumber)
pulseAnimation.repeatCount = Float.infinity
myImageView.layer.addAnimation(pulseAnimation, forKey: "opacity")
}
Upvotes: 1
Reputation: 112855
arc4random()
and arc4random_uniform()
are as random as you can get. No seeding is required and they are cryptographic quality.
For a range use arc4random_uniform()
instead of using the modular operator on arc4random()
.
What you don't want to use is rand()
.
Upvotes: 2