Instantly share code, notes, and snippets.

Embed
What would you like to do?
import UIKit
import QuartzCore
import PlaygroundSupport
class AnimatableSpriteLayer: CALayer {
var spriteSheetImage: UIImage? {
didSet {
setUpSpriteAnimation()
}
}
var spriteFrameSize: CGSize? {
didSet {
setUpSpriteAnimation()
}
}
convenience init(spriteSheetImage: UIImage?, spriteFrameSize: CGSize?) {
self.init()
self.spriteSheetImage = spriteSheetImage
self.spriteFrameSize = spriteFrameSize
setUpSpriteAnimation()
}
private func setUpSpriteAnimation() {
guard let spriteSheetImage = spriteSheetImage,
let spriteFrameSize = spriteFrameSize else { return }
minificationFilter = kCAFilterNearest
magnificationFilter = kCAFilterNearest
masksToBounds = true
contentsGravity = kCAGravityLeft
contents = spriteSheetImage.cgImage
bounds.size = spriteFrameSize
let frameCount = Int(spriteSheetImage.size.width / spriteFrameSize.width)
var frameOffsets = [CGFloat]()
for frameIndex in 0..<frameCount {
frameOffsets.append(CGFloat(frameIndex) / CGFloat(frameCount))
}
let spriteKeyframeAnimation = CAKeyframeAnimation(keyPath: "contentsRect.origin.x")
spriteKeyframeAnimation.values = frameOffsets
spriteKeyframeAnimation.duration = 0.7
spriteKeyframeAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
spriteKeyframeAnimation.repeatCount = .greatestFiniteMagnitude
spriteKeyframeAnimation.calculationMode = kCAAnimationDiscrete
add(spriteKeyframeAnimation, forKey: "spriteKeyframeAnimation")
speed = 0.0
}
func play() {
speed = 1.0
}
func pause() {
speed = 0.0
}
}
let rootView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 300.0, height: 300.0))
rootView.backgroundColor = .white
let spriteSheetImage = UIImage(named: "alucard")
let spriteFrameSize = CGSize(width: 176.0, height: 200.0)
let spriteLayer = AnimatableSpriteLayer(spriteSheetImage: spriteSheetImage, spriteFrameSize: spriteFrameSize)
spriteLayer.position = rootView.center
rootView.layer.addSublayer(spriteLayer)
spriteLayer.play()
PlaygroundPage.current.liveView = rootView
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment