Gasim
Gasim

Reputation: 8001

How to translate and animate CALayer on Z-Axis?

I am trying to translate a CALayer in Z-Axis to give user the feeling of object coming closer to the screen. But I can't get it to work. Here is my code:

func createCircle(size : CGFloat, color : UIColor) {
    let layer = CALayer();
    let parentLayer = self.visualView.layer;

    // layer testing properties 
    layer.backgroundColor = color.CGColor;
    layer.cornerRadius = size / 2.0;
    layer.borderWidth = 2.0;
    layer.frame = CGRectMake(CGFloat(arc4random() % uint(parentLayer.frame.width)), CGFloat(arc4random() % uint(parentLayer.frame.height)), size, size);       


    // transform properties
    let identity = CATransform3DIdentity;

    // have tried both -50 and +50 for the Z-Axis and got nothing.
    layer.transform = CATransform3DTranslate(identity, 0, 0, 50);

    // animation
    let animationGroup = self.createAnimationForLayer(layer);

    layer.addAnimation(animationGroup, forKey: nil);
    parentLayer.addSublayer(layer);
}

func createAnimationForLayer(layer : CALayer) -> CAAnimationGroup {
    let transformChange = CABasicAnimation(keyPath: "transform");
    transformChange.fromValue = NSValue(CATransform3D: layer.transform);
    transformChange.toValue = NSValue(CATransform3D: CATransform3DIdentity);

    let animationGroup = CAAnimationGroup();
    animationGroup.animations = [transformChange];
    animationGroup.duration = 1.0;
    animationGroup.delegate = self;
    animationGroup.setValue(layer, forKey: "animationLayer");
    animationGroup.fillMode = kCAFillModeForwards;
    return animationGroup;
}

The translation doesn't happen at all. The object doesn't move. I thought maybe the problem is at the translation itself but if I give value to X or Y, the object moves. Can't I use the Z-Axis in CALayer?

Upvotes: 2

Views: 1123

Answers (1)

jyliang
jyliang

Reputation: 198

  1. Add perspective projection: m34 = -1.0/d where d is distance between the imaginary camera and the screen.

  2. Set sublayerTransform to apply the perspective to all of its sublayers

    var transform = CATransform3DIdentity
    transform.m34 = -1.0/500.0
    self.visualView.layer.transform = transform
    self.visualView.layer.sublayerTransform = transform
    

Upvotes: 1

Related Questions