您的位置:首页 > 移动开发 > Swift

Swift实现洗牌动画效果

2016-12-25 23:24 519 查看
目标效果: 点击动画按钮之后每张牌各自旋转 散开到屏幕上半部分的任意位置之后回到初始位置 比较像LOL男刀的技能动画 : )

1: 创建卡牌对象

for _ in 0...49 {
let cardSet = UIImageView(image: UIImage(named: "cardBackLandscape"))
self.view.addSubview(cardSet)
cardSet.frame = self.landscapeCardBack.frame
self.cardSetList.append(cardSet)
}
NSNotificationCenter.defaultCenter().postNotificationName("setCreated", object: nil)


把每个卡牌作为UIImageView创建出来,为了之后对这些牌进行操作 我用数组把他们持有住 在同一位置创建好了之后 使用本地通知发送setCreated消息 告诉这个页面的观察者card set已经创建完毕 可以开始执行第二步动画

2: 首先需要把开始动画的按钮的用户交互关闭,如果开着的话连续点击每次都会创建50张牌,导致程序卡顿甚至挂掉

这里的delayTime是给线程加一个延迟时间 只是为了让动画不很生硬

每次循环给对应下标的card对象添加旋转动画,并且改变它的原点,我在用UIView动画实现这套动画之前想过给每张牌添加贝塞尔曲线,那样的话确实可控性更高,但是由于时间关系我还是只用了UIViewAnimation,给card添加的旋转动画是使用POP动画库实现的,这里使用的是Basic动画.这一步结束之后会把每张牌旋转并散开到不同的位置,在delayTime结束并触发本地通知发送shuffleFinished的时候,这个页面的观察者会执行下一部动画 也就是把每张牌还原到动画起点

func shuffleTheSet() {
self.shuffleButton.userInteractionEnabled = false
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName("shuffleFinished", object: nil)
}
for count in 0...49 {
UIView.animateWithDuration(0.3, animations: {
let cardRotateAnimation = POPBasicAnimation(propertyNamed: kPOPLayerRotation)
cardRotateAnimation.fromValue = 0
cardRotateAnimation.toValue = CGFloat(M_PI * 2.0)
cardRotateAnimation.duration = 1
//                cardRotateAnimation.duration = Double(count>5 ? count/2 : count/10)
cardRotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
self.cardSetList[count].layer.pop_addAnimation(cardRotateAnimation, forKey: "cardRotation")
self.cardSetList[count].frame.origin = CGPointMake(CGFloat(arc4random()) % (250 - 0 + 1) + 0, CGFloat(arc4random()) % (300 - 74 + 1) + 74)
self.view.layoutIfNeeded()
self.landscapeCardBack.removeFromSuperview()
})
}
}


3: 把每张牌的还原到初始位置,并把button的title设置为切牌状态.

for count in 0...49 {
UIView.animateWithDuration(0.3, animations: {
self.cardSetList[count].center = self.landscapeCardBack.center
})
self.view.layoutIfNeeded()
}
self.shuffleButton.userInteractionEnabled = true
self.shuffleButton.setTitle("Cut Card", forState: .Normal)


牌洗完之后的需求是切牌,由于时间原因下周继续更新后续动画效果…
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swift 动画