Get current CAAnimation transform value

前端 未结 4 676
感情败类
感情败类 2021-01-11 23:11

I want to access get the value of the transform scale at a point in time. Here is the animation creation :

    CABasicAnimation *grow = [CABasicAnimation ani         


        
相关标签:
4条回答
  • 2021-01-11 23:43

    swift version of @Duncan C answer will be:

    let currentValue = someView.layer.presentation()?.value(forKeyPath: "transform.scale")
    
    0 讨论(0)
  • 2021-01-11 23:46

    Swift 5: The nicest answer, in a function from Hacking With Swift

    func scale(from transform: CGAffineTransform) -> Double {
        return sqrt(Double(transform.a * transform.a + transform.c * transform.c))
    }
    
    0 讨论(0)
  • 2021-01-11 23:52

    The CALayer documentation describes presentationLayer quite clearly:

    The layer object returned by this method provides a close approximation of the layer that is currently being displayed onscreen. While an animation is in progress, you can retrieve this object and use it to get the current values for those animations.

    0 讨论(0)
  • 2021-01-12 00:01

    In Core Animation if an animation is "in flight" on a layer, the layer has a second layer property known as presentationLayer. That layer contains the values of the in-flight animation.

    Edited

    (With a nod to Mohammed, who took the time to provide an alternate answer for Swift)

    Use code like this:

    Objective-C

    CGFloat currentScale = [[layer.presentationLayer valueForKeyPath: @"transform.scale"] floatValue];
    

    Swift:

    let currentScale = layer.presentation()?.value(forKeyPath: "transform.scale") ?? 0.0
    

    Note that the Swift code above will return 0 if the layer does not have a presentation layer. That's a fail case that you should program for. It might be better to leave it an optional and check for a nil return.

    Edit #2:

    Note that as Kentzo pointed out in their comment, reading a value from an in-flight animation will give you a snapshot at an instant in time. The new value of the parameter you read (transform.scale in this example) will start to deviate from the reading you get. You should either pause the animation, or use the value you read quickly and get another value each time you need it.

    0 讨论(0)
提交回复
热议问题