I want to click stop/pause and the animation stop at that point, at some % between 0 and 1 alphaValue
I have not found a direct way to do it.
But here is a workaround.
At start of animation:
- get the alphaValue: initAlpha
- get the time
In the completion, if elapsed is less than the set duration (here 5.0), which means animation was stopped:
- compute elapsedTime since beginning of animation
- compute what should be alpha at this time, if "normal" endValue (0) is endAlpha and normalDuration (5.0):
let deltaAlpha = (initAlpha - endAlpha) * (elapsed / normalDuration)
- and set alpha inaccordingly:
self.view1.alphaValue = initAlpha - deltaAlpha
Full code should look like this:
@IBAction func startAnimation(_ sender: NSButton) {
let initAlpha = self.view1.alphaValue // Usually 1.0
let endAlpha = CGFloat(0)
let startTime = DispatchTime.now() // Precisely when animation starts
let fixedDuration = 5.0
var elapsedTime : Double = 0.0
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = fixedDuration // 5.0
self.view1.animator().alphaValue = endAlpha // 0
}) { // Completion
let endTime = DispatchTime.now()
elapsedTime = Double((endTime.uptimeNanoseconds - startTime.uptimeNanoseconds)) / 1_000_000_000 // Difference in seconds
if elapsedTime >= fixedDuration {
self.view1.alphaValue = initAlpha // return to initial value 1.0
} else { // Adjust proportionally
let deltaAlpha = (initAlpha - endAlpha) * (elapsedTime / fixedDuration)
self.view1.alphaValue = initAlpha - deltaAlpha
}
}
}