天天看点

Swift实现洗牌动画效果

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

1: 创建卡牌对象

for _ in . {
                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( * Double(NSEC_PER_SEC)))
        dispatch_after(delayTime, dispatch_get_main_queue()) {
            NSNotificationCenter.defaultCenter().postNotificationName("shuffleFinished", object: nil)
        }
        for count in . {
            UIView.animateWithDuration(, animations: {
                let cardRotateAnimation = POPBasicAnimation(propertyNamed: kPOPLayerRotation)
                cardRotateAnimation.fromValue = 
                cardRotateAnimation.toValue = CGFloat(M_PI * )
                cardRotateAnimation.duration = 
                //                cardRotateAnimation.duration = Double(count> ? count/ : count/)
                cardRotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
                self.cardSetList[count].layer.pop_addAnimation(cardRotateAnimation, forKey: "cardRotation")
                self.cardSetList[count].frame.origin = CGPointMake(CGFloat(arc4random()) % ( -  + ) + , CGFloat(arc4random()) % ( -  + ) + )
                self.view.layoutIfNeeded()
                self.landscapeCardBack.removeFromSuperview()
            })
        }
    }
           

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

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

牌洗完之后的需求是切牌,由于时间原因下周继续更新后续动画效果…

继续阅读