汤姆猫的小游戏,当我触发某个指令时,比如喝牛奶、吃东西等,会产生一个动画。今天我们来学习如何用帧动画来实现。
帧动画我们应该知道,这是播放动画的一般方法,通过在短时间内播放一组连续的图片来达到动画效果。
下面实例中只演示喝牛奶、吃东西这俩个动画,其他动画原理一样:
import UIKit class ViewController: UIViewController { //用于播放的UIImageView @IBOutlet weak var catIv: UIImageView!; //喝牛奶 @IBAction func drink() { //1.加载图片到数组中 var imgArray = [UIImage](); for var i = 0; i<81; ++i{ var imgName = i<10 ? "drink_0\(i)" : "drink_\(i)"; var image:UIImage = UIImage(named: imgName)!; imgArray.insert(image,atIndex: i); } //2.将数组添加到UIImageView中 self.catIv.animationImages = imgArray; //3.设置动画持续时间 self.catIv.animationDuration = Double(imgArray.count) * 0.1; //4.设置动画持续次数 self.catIv.animationRepeatCount = 1; //5.开启动画 self.catIv.startAnimating(); } //吃东西 @IBAction func eat() { //1.加载图片到数组中 var imgArray = [UIImage](); for var i = 0; i<40; ++i{ var imgName = i<10 ? "eat_0\(i)" : "eat_\(i)"; var image:UIImage = UIImage(named: imgName)!; imgArray.insert(image,atIndex: i); } //2.将数组添加到UIImageView中 self.catIv.animationImages = imgArray; //3.设置动画持续时间 self.catIv.animationDuration = Double(imgArray.count) * 0.1; //4.设置动画持续次数 self.catIv.animationRepeatCount = 1; //5.开启动画 self.catIv.startAnimating(); } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }原文:http://www.see-source.com/blog/300000109/763.html