NSView scale animation is not smooth

Viewed 244

I am trying to scale an NSView that is 56x56. The animation is applying scale of 0.95 and an alpha of 0.75, autoreverse and repeats infinitely. I have the animation working however the animation is extremely chunky (not smooth).

How can I use CAAnimationGroup and CABasicAnimation to animate these properties smoothly?

You can see the chunky animation in this gif

Animation Example

The animation code looks like the following

private func transformWithScale(_ scale: CGFloat) -> CATransform3D {
    let bounds = squareView.bounds
    let scale = scale != 0 ? scale : CGFloat.leastNonzeroMagnitude
    let xPadding = 0.5*bounds.width
    let yPadding = 0.5*bounds.height
    let translate = CATransform3DMakeTranslation(xPadding, yPadding, 0.0)
    return scale == 1.0 ? translate : CATransform3DScale(translate, scale, scale, 1.0)
}

func startAnimation() {
    let layer = squareView.layer!
    layer.removeAllAnimations()
    layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)

    let scaleAnimation = CABasicAnimation(keyPath: "transform")
    scaleAnimation.fromValue = transformWithScale(1.0)
    scaleAnimation.toValue = transformWithScale(0.95)

    let alphaAnimation = CABasicAnimation(keyPath: "opacity")
    alphaAnimation.fromValue = 1.0
    alphaAnimation.toValue = 0.75

    let group = CAAnimationGroup()
    group.duration = 0.8
    group.autoreverses = true
    group.timingFunction = CAMediaTimingFunction(name: .easeIn)
    group.repeatCount = .infinity
    group.animations = [scaleAnimation, alphaAnimation]

    layer.add(group, forKey: "scaleAndAlpha")
}
1 Answers

Try this one:

let container = NSView(frame: NSRect(x: 0, y: 0, width: 300, height: 300))
container.wantsLayer = true
container.layer?.backgroundColor = NSColor.blue.cgColor

let content = NSView(frame: NSRect(x: 0, y: 0, width: 150, height: 150))
content.wantsLayer = true
content.layer?.backgroundColor = NSColor.red.cgColor
container.addSubview(content)

let layer = content.layer!

let scaleAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
scaleAnimation.fromValue = CATransform3DScale(CATransform3DIdentity, 1, 1, 1)
scaleAnimation.toValue = CATransform3DScale(CATransform3DIdentity, 0.85, 0.85, 1)

let alphaAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity))
alphaAnimation.fromValue = 1.0
alphaAnimation.toValue = 0.75

let group = CAAnimationGroup()
group.duration = 0.8
group.autoreverses = true
group.timingFunction = CAMediaTimingFunction(name: .easeOut)
group.repeatCount = .infinity
group.animations = [scaleAnimation, alphaAnimation]

let center = CGPoint(x: container.bounds.midX, y: container.bounds.midY)
layer.position = center
layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
layer.add(group, forKey: nil)

PlaygroundPage.current.liveView = container
Related