Skip to content

Instantly share code, notes, and snippets.

@rickyngk
Last active May 5, 2016 08:13
Show Gist options
  • Save rickyngk/25f4d8b34adf83e07d34ee0f91a2b06b to your computer and use it in GitHub Desktop.
Save rickyngk/25f4d8b34adf83e07d34ee0f91a2b06b to your computer and use it in GitHub Desktop.
2d sprite animation with swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var animView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
animView.setAnimSpritesheet("player.png", rows: 3, cols: 7, fps: 12)
animView.animationRepeatCount = 0;
animView.startAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
typealias ImageData = CIImage
extension UIImageView {
func setAnimSpritesheet(fileName:String, rows:Int, cols:Int, fps:Int) -> Void {
if (rows > 0 && cols > 0) {
if let src:UIImage = UIImage(named:fileName)! {
if let ci_src:ImageData = ImageData.init(image: src)! {
let context = CIContext(options:nil)
let regionW:Int = Int(Int(src.size.width)/cols)
let regionH:Int = Int(Int(src.size.height)/rows)
var x = 0, y = 0
var regs:[UIImage] = [UIImage]()
if (regionH > 0 && regionW > 0) {
for _ in 1 ... rows {
for _ in 1 ... cols {
let cgimg = context.createCGImage(ci_src, fromRect: CGRect(x: x, y: y, width: regionW, height: regionH))
let uiimg = UIImage.init(CGImage: cgimg)
regs.append(uiimg)
x += regionW
}
x = 0
y += regionH
}
self.animationImages = regs
let totalFrames = rows*cols
let dur:Double = Double(totalFrames)/Double(fps)
self.animationDuration = dur
}
self.image = regs.last
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment