目標效果: 點擊動畫按鈕之后每張牌各自旋轉 散開到屏幕上半部分的任意位置之后回到初始位置 比較像LOL男刀的技能動畫 : )
1: 創建卡牌對象
1
2
3
4
5
6
7
|
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的時候,這個頁面的觀察者會執行下一部動畫 也就是把每張牌還原到動畫起點
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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設置為切牌狀態.
1
2
3
4
5
6
7
8
|
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洗牌動畫效果的實現方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/beatman_z/article/details/53876670