iOS--手把手教你一步一步完成搖骰子動畫

東閣堂主發表於2018-06-01

寫在前面

去年就已經上了搖骰子功能,今年把這個模組總結一下
,用到的知識點很多,但都是比較基礎的。
我先羅列一下知識點,骰子的數量可控,
根據不同的玩法返回對應的數值,要涉及到去重,搖一搖開啟動畫
1,UIImageView的動畫 --旋轉動畫
2,高階動畫--組動畫
3,玩法組合--隨機數產生,骰子數值回撥
4,加入系統搖一搖功能
5,閉包回撥,列舉型別運用
這裡只列出了部分程式碼,完整程式碼,請移步github 

複製程式碼

檢視原始碼:gitHub:DDGDiceAnimation

gif動畫效果不太明顯,請下載程式碼執行檢視真實效果

image

UIImageView的動畫

//也可用晃動動畫,這裡採用了圖片動畫
UIImageView 自己封裝好動畫,需要傳入圖片陣列
 //轉動骰子的載入
let myImages:[UIImage] = [UIImage(named:"7.png")!,UIImage(named:"8.png")!,UIImage(named:"9.png")!]
//骰子1的轉動圖片切換
let imageDong11 = UIImageView(frame: CGRect(x: 85.0, y: 115.0, width: 90.0,height: 90.0))
//設定圖片動畫切換時間
imageDong11.animationDuration = 0.1
//設定圖片動畫資源
imageDong11.animationImages = myImages
//開啟動畫
imageDong11.startAnimating()

複製程式碼

骰子1的組動畫

//設定動畫
let spin = CABasicAnimation(keyPath: "transform.rotation")
spin.duration = animations
spin.toValue = Double.pi * 16.0
//******************位置變化***************
//設定骰子1的位置變化
//注意不要染骰子運動到螢幕之外
let dice1Point = self.getRandomNumbers(8, lenth: UInt32(ScreenWidth))
//用關鍵幀動畫 ,設定四個點,按照這四個點移動
let p1 = CGPoint(x: CGFloat(dice1Point[0]), y: CGFloat(dice1Point[1]))
let p2 = CGPoint(x: CGFloat(dice1Point[2]), y: CGFloat(dice1Point[3]))
let p3 = CGPoint(x: CGFloat(dice1Point[4]), y: CGFloat(dice1Point[5]))
let p4 = CGPoint(x: CGFloat(dice1Point[6]), y: CGFloat(dice1Point[7]))
//把點轉換成NSValue陣列下一步要用
let keypoint = [NSValue(cgPoint: p1),NSValue(cgPoint: p2),NSValue(cgPoint: p3),NSValue(cgPoint: p4)]
//初始化動畫的屬性是位置動畫
let animation1 = CAKeyframeAnimation(keyPath: "position")
animation1.values = keypoint
animation1.duration = animations
imageDong11.layer.position = CGPoint(x: ScreenWidth / 2  - 60, y: ScreenHeight / 2.0 - 50)
 //骰子1的動畫組合
let animGroup1 = CAAnimationGroup()
animGroup1.animations = [animation1]
animGroup1.duration = animations
//動畫結束時會呼叫代理方法,將計算好的骰子動畫傳給控制器
animGroup1.delegate = self
imageDong11.layer.add(animGroup1, forKey: "position")

//隨機產生不同的號碼
func getRandomNumbers(_ count:Int,lenth:UInt32) -> [Int] {
    var randomNumbers = [Int]()
    for _ in 0...(count - 1) {
        var number = Int()
        number = Int(arc4random_uniform(lenth))+1
        while randomNumbers.contains(number) {
            number = Int(arc4random_uniform(lenth))+1
        }
            randomNumbers.append(number)
        }
        return randomNumbers
    }

複製程式碼

加入搖一搖動畫

加入系統的搖一搖動畫(晃動手機就呼叫)
這個比較簡單
//匯入系統庫
import AudioToolbox
//呼叫並重寫系統方法
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
        if motion == .motionShake {
            if isDiceMoving == false {
                //開始動畫
                self.diceAnimationStart()
            }
        }
}
//模擬器呼叫方法
點選模擬器
Simulator -> Hardware -> Shake Gestrue
複製程式碼

動畫結束時的回撥

func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
    //隱藏圖片
    image1.isHidden = true
    //停止圖片的動畫
    imageDong1.stopAnimating()
    //色子1
    let dice1 = Int(arc4random_uniform(6)) + 1
    //設定骰子停止時的顯示的圖片
    imageDong1.image = UIImage(named: "\(dice1).png")
    //動畫結束時將骰子的陣列傳出到控制器
    self.animationStop(true, diceArr: [])
    補充,骰子的玩法型別比較多
    "和值","三同號","二同號","三不同號","二不同號"
    所以定義了一個  列舉enum
    //色子玩法型別
    enum DiceAnimationType {
        //和值
        case hzType
        //三同號
        case same3Type
        //二同號
        case same2Type
        //三不同號
        case diff3Type
        //二不同號
        case diff2Type
    }

}
複製程式碼

完成動畫回撥的完整程式碼

    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        image1.isHidden = true
        image2.isHidden = true
        image3.isHidden = true
        
        imageDong1.stopAnimating()
        imageDong2.stopAnimating()
        imageDong3.stopAnimating()
        
        //產生隨機數
        switch self.diceAnimationType {
        case .hzType:
            //色子1
            let dice1 = Int(arc4random_uniform(6)) + 1
            imageDong1.image = UIImage(named: "\(dice1).png")
            //色2
            let dice2 = Int(arc4random_uniform(6)) + 1
            imageDong2.image = UIImage(named: "\(dice2).png")
            //色3
            let dice3 = Int(arc4random_uniform(6)) + 1
            imageDong3.image = UIImage(named: "\(dice3).png")
            self.animationStop(true, diceArr: [dice1,dice2,dice3])
        case .diff2Type:
            let diff2Arr = self.getRandomNumbers(2,lenth: 5)
            //色子1
            imageDong1.image = UIImage(named: "\(diff2Arr[0]).png")
            //色2
            imageDong2.image = UIImage(named: "\(diff2Arr[1]).png")
            //色3
            let dice3 = Int(arc4random_uniform(6))
            imageDong3.image = UIImage(named: "\(dice3).png")
            self.animationStop(true, diceArr: diff2Arr)
        case .diff3Type:
            //從1到4
            let diff3Arr0 = self.getRandomNumbers(1,lenth: 4)[0]
            //從2到5
            var diff3Arr1 = self.getRandomNumbers(1,lenth: 4)[0]
            //從3到6
            var diff3arr2 = self.getRandomNumbers(1,lenth: 4)[0]
            if diff3Arr0 == 1 {
                diff3Arr1 = self.getRandomNumbers(1,lenth: 4)[0] + 1
                diff3arr2 = diff3arr2 + 2
                if diff3Arr1 >= diff3arr2 {
                    diff3arr2 = diff3Arr1 + 1
                }
            } else if diff3Arr0 == 2 {
                diff3Arr1 = self.getRandomNumbers(1, lenth: 3)[0] + 2
                diff3arr2 = self.getRandomNumbers(1, lenth: 3)[0] + 3
                if diff3Arr1 >= diff3arr2 {
                    diff3arr2 = diff3Arr1 + 1
                }
            } else if diff3Arr0 == 3 {
                diff3Arr1 = self.getRandomNumbers(1, lenth: 2)[0] + 3
                diff3arr2 = self.getRandomNumbers(1, lenth: 2)[0] + 4
                if diff3Arr1 >= diff3arr2 {
                    diff3arr2 = diff3Arr1 + 1
                }
            } else {
                diff3Arr1 = 5
                diff3arr2 = 6
            }
            //色子1
            imageDong1.image = UIImage(named: "\(diff3Arr0).png")
            //色2
            imageDong2.image = UIImage(named: "\(diff3Arr1 ).png")
            //色3
            imageDong3.image = UIImage(named: "\(diff3arr2 ).png")
            self.animationStop(true, diceArr:[diff3Arr0 ,diff3Arr1  ,diff3arr2 ])
        case .same2Type:
            let same2Arr = self.getRandomNumbers(2,lenth: 6)
            //色1
            imageDong1.image = UIImage(named: "\(same2Arr[0]).png")
            //色2
            imageDong2.image = UIImage(named: "\(same2Arr[0]).png")
            //色3
            imageDong3.image = UIImage(named: "\(same2Arr[1]).png")
            self.animationStop(true, diceArr: [same2Arr[0],same2Arr[0],same2Arr[1]])
        case .same3Type:
            let same3Arr = self.getRandomNumbers(1,lenth: 6)
            //色1
            imageDong1.image = UIImage(named: "\(same3Arr[0]).png")
            //色2
            imageDong2.image = UIImage(named: "\(same3Arr[0]).png")
            //色3
            imageDong3.image = UIImage(named: "\(same3Arr[0]).png")
            self.animationStop(true, diceArr: [same3Arr[0],same3Arr[0],same3Arr[0]])
        }
    }
複製程式碼

DDGDiceAnimation is available under the MIT license. See the LICENSE file for more info. 如果有問題歡迎提出,QQ:532835032 ,如果對您有幫助,希望您動動滑鼠,不吝給個star.!

instructions (備註)

個人其他相關庫附上鍊接,希望可以幫到你:

檔案快取OC版:github.com/dudongge/DD…

檔案快取Swift版:github.com/dudongge/DD…

圖片截圖庫:github.com/dudongge/DD…

相關文章