Swift:动画CALayer

问题描述 投票:3回答:1

在下面的代码中,当用户按住屏幕(longPressGestureRecognizer)时,我试图从屏幕的左侧到屏幕的右侧制作一个CALayer动画。当用户抬起手指时,CALayer会暂停。

var l = CALayer()
var holdGesture = UILongPressGestureRecognizer()
let animation = CABasicAnimation(keyPath: "bounds.size.width")

override func viewDidLoad() {
    super.viewDidLoad()
    setUpView()
}

func setUpView(){
    l.frame = CGRect(x: 0, y: 0, width: 0, height: 10)
    l.backgroundColor = UIColor.redColor().CGColor

    self.view.addGestureRecognizer(holdGesture)
    holdGesture.addTarget(self, action:"handleLongPress:")
}

func handleLongPress(sender : UILongPressGestureRecognizer){

    if(sender.state == .Began) { //User is holding down on screen
        print("Long Press Began")
        animation.fromValue = 0
        animation.toValue = self.view.bounds.maxX * 2
        animation.duration = 30
        self.view.layer.addSublayer(l)
        l.addAnimation(animation, forKey: "bounds.size.width")
    }
    else { //User lifted Finger
        print("Long press ended")
        print("l width: \(l.bounds.size.width)")
        pauseLayer(l)
    }
}

func pauseLayer(layer : CALayer){
    var pausedTime : CFTimeInterval = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
    layer.speed = 0.0
    layer.timeOffset = pausedTime
}

我有两个问题:

1)当我在动画(用户松开手指)后打印CALayer的宽度时,其始终为0。我对宽度进行动画处理,并对其进行扩展,因此,我不知道为什么它不给我新的宽度CALayer。

2)用户抬起手指,然后再次按住之后,CALayer消失。我需要它保留在屏幕上,并创建另一个CALayer,我不以任何方式删除它,因此我不明白为什么它也消失了。我检查了对象仍然存在的内存。

更新为问题2的更新:我相信要创建另一个CALayer,我不能只是再次添加该层,我必须创建一个副本或创建一个可以添加该层的UIView。我仍然不明白为什么它消失了。

ios swift animation calayer uilongpressgesturerecogni
1个回答
6
投票

基本上,当用户按住时,您试图调整图层的大小。这是一个可用于调整给定图层大小的函数:

如果希望将原点固定在左侧,则需要先设置图层的锚点:

layer.anchorPoint = CGPointMake(0.0, 1);

func resizeLayer(layer:CALayer, newSize: CGSize) {

    let oldBounds = layer.bounds;
    var newBounds = oldBounds;
    newBounds.size = size;


    //Ensure at the end of animation, you have proper bounds
    layer.bounds = newBounds

    let boundsAnimation = CABasicAnimation(keyPath: "bounds")
    positionAnimation.fromValue = NSValue(CGRect: oldBounds)
    positionAnimation.toValue = NSValue(CGRect: newBounds)
    positionAnimation.duration = 30
} 

对于您而言,我不确定您在哪里恢复暂停的图层。还要观察用户每次点击时,都会在handleLongPress方法中添加一个新动画!这会产生不良影响。理想情况下,您只需要第一次启动动画,然后再恢复刚刚开始的暂停动画即可。

//Flag that holds if the animation already started..
var animationStarted = false

func handleLongPress(sender : UILongPressGestureRecognizer){

  //User is holding down on screen
  if(sender.state == .Began){

    if(animationStarted == false){
      let targetBounds =  CalculateTargetBounds() //Implement this to your need
      resizeLayer(layer, targetBounds)
      animationStarted = true
    }else {
      resumeLayer(layer)
    }
  }else {
    pauseLayer(layer)
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.