Search code examples
iosswiftswift3caanimation

NSValue valueWithCATransform3D: in Swift3


How to translate the following animation into Swift3?

CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
scaleAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
scaleAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(2.5, 2.5, 1)];

What I currently have is

let circleEnlargeAnimation = CABasicAnimation(keyPath: "transform.scale")
circleEnlargeAnimation.fromValue = CATransform3DIdentity
circleEnlargeAnimation.toValue = CATransform3DMakeScale(10.0, 10.0, 1.0)

But my animation is not working... The following is the full animation code:

    let shapeLayer = CAShapeLayer()
    let center = CGPoint(x: sampleButton.bounds.width/2.0, y: sampleButton.bounds.height/2.0)
    let radius = CGFloat(10.0)

    let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0.0, endAngle: (CGFloat(360.0 * M_PI) / 180.0), clockwise: true)
    shapeLayer.path = path.cgPath
    shapeLayer.fillColor = UIColor.white.cgColor
    shapeLayer.strokeColor = UIColor.white.cgColor
    shapeLayer.lineCap = kCALineCapRound

    shapeLayer.frame = sampleButton.bounds
    let circleEnlargeAnimation = CABasicAnimation(keyPath: "transform.scale")
    circleEnlargeAnimation.fromValue = CATransform3DIdentity
    circleEnlargeAnimation.toValue = CATransform3DMakeScale(10.0, 10.0, 1.0)
    circleEnlargeAnimation.duration = 1.0
    shapeLayer.add(circleEnlargeAnimation, forKey: nil)

    sampleButton.layer.addSublayer(shapeLayer)

It only shows a circle but is not animating...


Solution

  • You should either use the key transform.scale with a scalar numeric value or transform with a matrix value. See Key Value Coding Extensions in Core Animation Programming Guide for a full list of available keys.

    You can create a matrix value for instance with:

    NSValue(caTransform3D:CATransform3DMakeScale(10.0, 10.0, 1.0))