如何在Z轴上翻译和动画CALayer?

时间:2015-04-20 11:39:56

标签: ios core-animation calayer

我正在尝试在Z轴中翻译CALayer,让用户感觉物体更接近屏幕。但我无法让它发挥作用。这是我的代码:

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;
}

翻译根本没有发生。物体不会移动。我想也许问题出在翻译本身,但如果我给X或Y赋值,那么对象就会移动。我不能在CALayer中使用Z轴吗?

1 个答案:

答案 0 :(得分:1)

  1. 添加透视投影:m34 = -1.0 / d,其中d是虚拟相机与屏幕之间的距离。

  2. 设置sublayerTransform以将透视应用于其所有子图层

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