I am currently overlaying some text in a video using the AVMutableComposition, I would like to change the string repeatedly based on some time interval. I am trying to use the Core Animation to achieve this; however, the string property does not seem to be animatable. Is there any other way to achieve the goal? Thanks.
Code (not working):
func getSubtitlesAnimation(withFrames frames: [String], duration: CFTimeInterval)->CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath:"string")
animation.calculationMode = kCAAnimationDiscrete
animation.duration = duration
animation.values = frames
animation.keyTimes = [0,0.5,1]
animation.repeatCount = Float(frames.count)
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
animation.beginTime = AVCoreAnimationBeginTimeAtZero
return animation
}
String is not an animatable path on a CATextLayer. Here is the list of keyPaths that you can use on any CALayer.
Some other important things about using Core Animation with AVFoundation.
All animations have to have removedCompletion of false.
You can only apply one key path animation to a layer once. Meaning if you want to add an opacity of fade in and fade out it needs to be combined into a single keyframe animation. In core animation you could use beginTime and apply two different opacity animations but in my experience with AVFoundation and Core Animation this does not work. Because of this you will have to figure out the key times and values for what you would want to occur if you wanted to use two different (ex opacity) animations on the same keypath for the CALayer.
Your discrete curve will still work but you will have to work out the keytimes and values.
Because string is not available as an animatable property the next best thing would be to use multiple CATextLayers and fade them in one after the other. Here is an example. Replace CACurrentMediaTime() with AVCoreAnimationBeginTimeAtZero for use with AVFoundation. This was just an example so you could visualize what you want.
Example1Using-Discrete
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//center the frame
let textFrame = CGRect(x: (self.view.bounds.width - 200)/2, y: (self.view.bounds.height - 100)/2, width: 200, height: 50)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
//animation spacing could be a negative value of half the animation to appear to fade between strings
self.animateText(subtitles: ["Hello","Good Morning","Good Afternoon","Good Evening","Goodnight","Goodbye"], duration: 2, animationSpacing: 0, frame: textFrame, targetLayer: self.view.layer)
}
}
func animateText(subtitles:[String],duration:Double,animationSpacing:Double,frame:CGRect,targetLayer:CALayer){
var currentTime : Double = 0
for x in 0..<subtitles.count{
let string = subtitles[x]
let textLayer = CATextLayer()
textLayer.frame = frame
textLayer.string = string
textLayer.font = UIFont.systemFont(ofSize: 20)
textLayer.foregroundColor = UIColor.black.cgColor
textLayer.fontSize = 20.0
textLayer.alignmentMode = kCAAlignmentCenter
let anim = getSubtitlesAnimation(duration: duration, startTime: currentTime)
targetLayer.addSublayer(textLayer)
textLayer.add(anim, forKey: "opacityLayer\(x)")
currentTime += duration + animationSpacing
}
}
func getSubtitlesAnimation(duration: CFTimeInterval,startTime:Double)->CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath:"opacity")
animation.duration = duration
animation.calculationMode = kCAAnimationDiscrete
//have to fade in and out with a single animation because AVFoundation
//won't allow you to animate the same propery on the same layer with
//two different animations
animation.values = [0,1,1,0,0]
animation.keyTimes = [0,0.001,0.99,0.999,1]
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeBoth
//Replace with AVCoreAnimationBeginTimeAtZero for AVFoundation
animation.beginTime = CACurrentMediaTime() + startTime
return animation
}
}
EXAMPLE2-Using a long fade-Gif Attached
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//center the frame
let textFrame = CGRect(x: (self.view.bounds.width - 200)/2, y: (self.view.bounds.height - 100)/2, width: 200, height: 50)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
//animation spacing could be a negative value of half the animation to appear to fade between strings
self.animateText(subtitles: ["Hello","Good Morning","Good Afternoon","Good Evening","Goodnight","Goodbye"], duration: 4, animationSpacing: -2, frame: textFrame, targetLayer: self.view.layer)
}
}
func animateText(subtitles:[String],duration:Double,animationSpacing:Double,frame:CGRect,targetLayer:CALayer){
var currentTime : Double = 0
for x in 0..<subtitles.count{
let string = subtitles[x]
let textLayer = CATextLayer()
textLayer.frame = frame
textLayer.string = string
textLayer.font = UIFont.systemFont(ofSize: 20)
textLayer.foregroundColor = UIColor.black.cgColor
textLayer.fontSize = 20.0
textLayer.alignmentMode = kCAAlignmentCenter
let anim = getSubtitlesAnimation(duration: duration, startTime: currentTime)
targetLayer.addSublayer(textLayer)
textLayer.add(anim, forKey: "opacityLayer\(x)")
currentTime += duration + animationSpacing
}
}
func getSubtitlesAnimation(duration: CFTimeInterval,startTime:Double)->CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath:"opacity")
animation.duration = duration
//have to fade in and out with a single animation because AVFoundation
//won't allow you to animate the same propery on the same layer with
//two different animations
animation.values = [0,0.5,1,0.5,0]
animation.keyTimes = [0,0.25,0.5,0.75,1]
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeBoth
//Replace with AVCoreAnimationBeginTimeAtZero for AVFoundation
animation.beginTime = CACurrentMediaTime() + startTime
return animation
}
}
RESULT:
Duration of 2 seconds in and 2 seconds out. Could be immediate.
Solution for text animation using CATextLayer and CAKeyframeAnimation. Right now the string property is animate-able. Idk how was it in the past.
func addTextLayer(to layer: CALayer) {
let myAnimation = CAKeyframeAnimation(keyPath: "string");
myAnimation.beginTime = 0;
myAnimation.duration = 1.0;
myAnimation.values = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
myAnimation.fillMode = CAMediaTimingFillMode.forwards;
myAnimation.isRemovedOnCompletion = false;
myAnimation.repeatCount = 1;
let textLayer = CATextLayer();
textLayer.frame = CGRect(x: 200, y: 300, width: 100, height: 100);
textLayer.string = "0";
textLayer.font = UIFont.systemFont(ofSize: 20)
textLayer.foregroundColor = UIColor.black.cgColor
textLayer.fontSize = 40.0
textLayer.alignmentMode = .center
textLayer.add(myAnimation, forKey: nil);
layer.addSublayer(textLayer);
}
Solution for Swift 5:
like the answer from #agibson007
optimized for a duration of 0.25, faster wasn´t possible. (problems with fading / flicker)
func animateText(subtitles:[String],duration:Double,animationSpacing:Double,frame:CGRect,targetLayer:CALayer){
var currentTime : Double = 0
for x in 0..<subtitles.count{
let textLayer = CATextLayer()
textLayer.frame = frame
textLayer.string = subtitles[x]
textLayer.font = UIFont.systemFont(ofSize: 20)
textLayer.foregroundColor = UIColor.black.cgColor
textLayer.fontSize = 40.0
textLayer.alignmentMode = .center
let anim = getSubtitlesAnimation(duration: duration, startTime: currentTime)
textLayer.add(anim, forKey: "opacityLayer\(x)")
targetLayer.addSublayer(textLayer)
currentTime += duration + animationSpacing
}
}
func getSubtitlesAnimation(duration: CFTimeInterval,startTime:Double)->CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath:"opacity")
animation.duration = duration
animation.calculationMode = .discrete
animation.values = [0,1,1,0,0]
animation.keyTimes = [0,0.00000001,0.999,0.999995,1]
animation.isRemovedOnCompletion = false
animation.fillMode = .both
animation.beginTime = AVCoreAnimationBeginTimeAtZero + startTime // CACurrentMediaTime() <- NO AV Foundation
return animation
}
let steps = 0.25
let duration = 8.0
let textFrame = CGRect( x: (videoSize.width / 2) - (90 / 2) , y: videoSize.height * 0.2, width: 90, height: 50)
var subtitles:[String] = []
for i in 0...Int(duration / steps) {
let time = i > 0 ? steps * Double(i) : Double(i)
subtitles.append(String(format: "%0.1f", time) )
}
animateText(subtitles: subtitles, duration: steps, animationSpacing: 0, frame: textFrame, targetLayer: layer)
Try to think how subtitles are added in a movie?
A subtitle file contains time stamp values like, 00:31:21 : "Some text". So when the seekbar of a movie is at 00:31:21, you see "Some text" as the subtitle.
Similarly fo your requirement, you would need multiple CATextLayers which have animations corresponding to them (same or different for each CATExtLayer). When one CATextLayer animation ends, you can fade in your second CATextLayer and Fadeout the first one.
Last time I did this I remember, animations can be grouped and you can actually specify start point of an animation. Check beginTime property of CABasicAnimation
Related
I'm using a UIViewPropertyAnimator to animate the position of a view. But, I also want to animate CALayer properties like borderColor along with it. Currently, it doesn't animate and instantly changes at the start, like this:
Here's my code:
class ViewController: UIViewController {
var animator: UIViewPropertyAnimator?
let squareView = UIView(frame: CGRect(x: 0, y: 40, width: 80, height: 80))
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(squareView)
squareView.backgroundColor = UIColor.blue
squareView.layer.borderColor = UIColor.green.cgColor
squareView.layer.borderWidth = 6
animator = UIViewPropertyAnimator(duration: 2, curve: .easeOut, animations: {
self.squareView.frame.origin.x = 100
self.squareView.layer.borderColor = UIColor.red.cgColor
})
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.animator?.startAnimation()
}
}
}
I looked at this question, How to synchronously animate a UIView and a CALayer, and the answer suggested using "an explicit animation, like a basic animation." It said,
If the timing function and the duration of both animations are the same then they should stay aligned.
However, if I use CABasicAnimation, I lose all the benefits of UIViewPropertyAnimator, like timing and stopping in the middle. I will also need to keep track of both. Is there any way to animate CALayer properties with UIViewPropertyAnimator?
CABasicAnimation has timing as well as keyframe animation to stop in the middle. But, to replicate your animation above:
squareView.layer.transform = CATransform3DMakeTranslation(100, 0, 0)
let fromValue = squareView.transform
let toValue = 100
let translateAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
translateAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
translateAnimation.fromValue = fromValue
translateAnimation.toValue = toValue
translateAnimation.valueFunction = CAValueFunction(name: .translateX)
let fromColor = squareView.layer.borderColor
let toColor = UIColor.red.cgColor
let borderColorAnimation = CABasicAnimation(keyPath: "borderColor")
borderColorAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
borderColorAnimation.fromValue = fromColor
borderColorAnimation.toValue = toColor
let groupAnimation = CAAnimationGroup()
groupAnimation.animations = [translateAnimation, borderColorAnimation]
groupAnimation.duration = 5
squareView.layer.add(groupAnimation, forKey: nil)
Here I have been trying so long to create a custom animated progress bar.
I'm trying to move a view from screen's one end to second end with resizing.
view's frmae is (0, 100, 10, 4)
What I want is...
At start of animation view should be at its initial position, lets say at (0, 100)
in the middle of the animation view will be at the middle of the screen and its width will be increased to 100px.
at the end of the animation view will be at screen's second end. and frame of the view will be at, lets say (400, 100) and width off the view will be again back to 10px
The whole progress should be reversed also.
UIButton Action method
var mainView = UIView()
#IBAction func btnTapped(_ sender: UIButton) {
let rect = CGRect(x: 0, y: 300, width: 10, height: 4)
mainView = UIView(frame: rect)
mainView.backgroundColor = UIColor.black
self.view.addSubview(mainView)
animate()
}
Animation Method
func animate() {
let theAnimationTranslationX = CABasicAnimation(keyPath: "transform.translation.x")
theAnimationTranslationX.fromValue = mainView.bounds.minX
theAnimationTranslationX.toValue = 400
let scaleAnimate:CABasicAnimation = CABasicAnimation(keyPath: "transform.scale.x")
scaleAnimate.fromValue = NSValue(caTransform3D: CATransform3DMakeScale(1, 1, 1))
scaleAnimate.toValue = NSValue(caTransform3D: CATransform3DMakeScale(1.2, 0, 0))
let group = CAAnimationGroup()
group.autoreverses = true
group.repeatCount = .greatestFiniteMagnitude
group.animations = [theAnimationTranslationX]//, scaleAnimate]
group.duration = 2
group.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
mainView.layer.add(group, forKey: "animation")
}
I'm not getting the desired animation effect.
Is there any other way to do so or is it possible with any other way please suggest me.
Thanks for you time and any help will be appreciated.
EDIT:
The final animation should look like...
I'd like to create a CASpringAnimation for rotation that ends where it began. Here's some working code that doesn't end where it began (but otherwise is what I'm looking for):
func spring(view: UIView) -> CASpringAnimation{
let animation = CASpringAnimation(keyPath: "transform")
animation.damping = 0.5
animation.initialVelocity = 70
animation.mass = 0.04
animation.stiffness = 12
animation.duration = 1.2
animation.toValue = CATransform3DRotate(CATransform3DMakeAffineTransform(view.transform),
CGFloat(M_PI)/32, // Must be non-zero 😕
0, 0, 1)
return animation
}
And here's how you'd use it:
let animation = spring(view: viewToAnimate)
viewToAnimate.layer.add(animation, forKey: nil)
When I set the angle (beside the comment in CATransform3DRotate) to 0, the animation doesn't work! Any ideas on how to get a spring rotation with the same start and end angles? Thanks for reading.
By adding a CABasicAnimation that animates to 0° over the same time duration, and also by tweaking the spring animation parameters, I've got something that looks pretty good (tested for iOS 10):
#IBAction func springButtonTapped(_ sender: UIButton) { // Attach to the view you'd like animated
let springAnim = spring(view:sender)
sender.layer.add(springAnim, forKey: nil)
let correctionAnim = correct(view:sender)
sender.layer.add(correctionAnim, forKey: nil)
}
func correct(view: UIButton) -> CABasicAnimation{
let animation = CABasicAnimation(keyPath: "transform")
animation.duration = 0.3
animation.toValue = CATransform3DRotate(CATransform3DMakeAffineTransform(view.transform),
0,
0, 0, 1)
return animation
}
func spring(view: UIView) -> CASpringAnimation{
let animation = CASpringAnimation(keyPath: "transform")
animation.damping = 0.0
animation.initialVelocity = 80
animation.mass = 0.04
animation.stiffness = 50
animation.duration = 0.3
animation.toValue = CATransform3DRotate(CATransform3DMakeAffineTransform(view.transform),
CGFloat(M_PI)/64,
0, 0, 1)
return animation
}
What would be the reason for CAKeyframeAnimation objects to not be able to animate simultaneously in a CAAnimationGroup, but it does if being added individually to a CALayer?
A code snippet to describe this:
// The following is a part of CALayer extension function
let quadAnimation = CAKeyframeAnimation(keyPath: "transform")
quadAnimation.duration = 1.0
quadAnimation.repeatCount = 1
quadAnimation.removedOnCompletion = false
quadAnimation.fillMode = kCAFillModeForwards
quadAnimation.beginTime = CACurrentMediaTime()
quadAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.743, 0, 0.833, 0.833)
// Note:
// AGK-based methods come from a geometry manipulation library https://github.com/agens-no/AGGeometryKit
//
var values: [NSValue] = []
let numberOfFrames = 30
for frame in 0..<numberOfFrames {
let p = AGKEaseOutWithBezier(CGFloat(frame) / CGFloat(numberOfFrames))
let quad = AGKQuadInterpolate(quad1, quad2, CGFloat(p))
let innerQuad = AGKQuadMove(quad, -self.position.x, -self.position.y)
let transform = CATransform3DWithAGKQuadFromBounds(innerQuad, CGRect(origin: CGPoint.zero, size: self.boundsSize))
let value = NSValue(CATransform3D: transform)
values += [value]
}
quadAnimation.values = values
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.keyTimes = [0, 1]
opacityAnimation.values = [0, 1]
opacityAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.167, 0.167, 0.833, 0.833)
opacityAnimation.duration = 0.5
opacityAnimation.beginTime = CACurrentMediaTime() + 0.5
opacityAnimation.fillMode = kCAFillModeForwards
let animationBlockDelegate = AGKCALayerAnimationBlockDelegate()
animationBlockDelegate.onStart = {
self.quadrilateral = quad2
}
let animationGroup = CAAnimationGroup()
animationGroup.animations = [quadAnimation, opacityAnimation]
animationGroup.duration = quadAnimation.duration + opacityAnimation.duration + 0.5
animationGroup.delegate = animationBlockDelegate
CATransaction.begin()
CATransaction.setCompletionBlock {
// Completion block handler
}
self.addAnimation(animationGroup, forKey: "transformOpacityAnimationKey")
CATransaction.commit()
The opacity will be animated given the right timingFunction and beginTime, but the CA3DTransform values are not animated at all.
All of the above works fine if I added the animation individually to the layer:
self.addAnimation(quadAnimation, forKey:"quadAnimation")
self.addAnimation(opacityAnimation, forKey: "opacityAnimation")
With each animation quadAnimation and opacityAnimation process delegated to AGKCALayerAnimationBlockDelegate()
I was reading the 12th number of Objc.io and encountered a problem when trying the first pieces of code.
In the first part "A Basic Animation" the last piece of code uses byValue to interpolate a property using initial property value and adding byValue.
So I tried the code in my project and discovered it wasn't working and had a really strange behavior.
Here's a very short gif illustrating the problem :
And here's the only code I'm using :
class ViewController: UIViewController {
var rocket1: UIView!
var rocket2: UIView!
override func viewDidLoad() {
super.viewDidLoad()
rocket1 = UIView(frame: CGRect(x: 20, y: 100, width: 50, height: 20))
rocket1.backgroundColor = UIColor.redColor()
rocket2 = UIView(frame: CGRect(x: 20, y: 150, width: 50, height: 20))
rocket2.backgroundColor = UIColor.blueColor()
self.view.addSubview(rocket1)
self.view.addSubview(rocket2)
}
#IBAction func button() {
let animation = CABasicAnimation(keyPath: "position.x")
animation.byValue = 300
animation.duration = 1
rocket1.layer.addAnimation(animation, forKey: "basic")
rocket1.layer.position.x += 300
animation.beginTime = CACurrentMediaTime() + 0.5
rocket2.layer.addAnimation(animation, forKey: "basic")
rocket2.layer.position.x += 300
}
}
If you want to try the project here's the full project (use iPhone 6 simulator or shapes will be hidden because 5S is too "short") : https://dl.dropboxusercontent.com/u/378166/VCoreAnimation.zip
you should create a completion block for this animation like this:
#IBAction func button() {
let animation = CABasicAnimation(keyPath: "position.x")
animation.byValue = 300
animation.duration = 1
CATransaction.begin()
CATransaction.setCompletionBlock({
rocket1.layer.position.x += 300
})
rocket1.layer.addAnimation(animation, forKey: "basic")
CATransaction.commit()
animation.beginTime = CACurrentMediaTime() + 0.5
CATransaction.begin()
CATransaction.setCompletionBlock({
rocket2.layer.position.x += 300
})
rocket2.layer.addAnimation(animation, forKey: "basic")
CATransaction.commit()
}
In this case we need 2 CATransaction blocks since we have 2 animations running with a time diference from each other.