I'm experimenting with animating CAShapeLayer paths with CASpringAnimation. The expected result is a 'morphing' between shapes that acts 'springy'.
I have a basic code example between a circle and square path as below, however the end result is a spring animation that does not 'overshoot' past the final, larger square path, which is the expected behaviour.
My code is:
let springAnimation = CASpringAnimation(keyPath: "path")
springAnimation.damping = 1
springAnimation.duration = springAnimation.settlingDuration
springAnimation.fromValue = standardCirclePath().cgPath
springAnimation.toValue = standardSquarePath().cgPath
circleLayer.add(springAnimation, forKey: nil) // Where circleLayer (red background) is a sublayer of a basic UIView in the frame (blue background)
I got my paths from this answer.
Is there a way with CASpringAnimation to achieve this for a CAShapeLayer path transform? Otherwise, what are the alternatives?
Hello I had been working on your question and this is my results, the glitches on the gif is because my gif converter is very bad converter
this is the code
class ViewController: UIViewController {
#IBOutlet weak var animatableVIew: UIView!
var isBall = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func startAnimation(sender: AnyObject) {
isBall = !isBall
let springAnimation = CASpringAnimation(keyPath: "cornerRadius")
let halfWidth = animatableVIew.frame.width / 2
let cornerRadius: CGFloat = isBall ? halfWidth : 0
springAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
springAnimation.fromValue = isBall ? 0 : halfWidth ;
springAnimation.toValue = cornerRadius;
springAnimation.damping = 7
springAnimation.duration = springAnimation.settlingDuration
animatableVIew.layer.cornerRadius = cornerRadius
let springAnimation2 = CAKeyframeAnimation(keyPath: "transform.scale")
springAnimation2.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
springAnimation2.values = [1,0.9,1.4,0.8,1]
springAnimation2.keyTimes = [ 0, (1 / 6.0), (3 / 6.0), (5 / 6.0), 1 ];
springAnimation2.duration = springAnimation.settlingDuration * 0.5
let groupSpringAnimation = CAAnimationGroup()
groupSpringAnimation.animations = [springAnimation,springAnimation2]
groupSpringAnimation.duration = springAnimation.settlingDuration
groupSpringAnimation.beginTime = 0;
animatableVIew.layer.addAnimation(groupSpringAnimation, forKey: "group")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I hope this helps you
Related
I must admit I have no clue how to do this in iOS -
Here's some code that makes a nice dotted line:
Now, I want that line to "run" upwards:
So, every one second it will move upwards by, itemLength * 2.0.
Of course, it would wrap around top to bottom.
So, DottedVertical should just do this completely on its own.
Really, how do you do this in iOS?
It would be great if the solution is general and will "scroll" any I suppose layer or drawn thing.
In say a game engine it's trivial, you just animate the offset of the texture. Can you perhaps offset the layer, or something, in iOS?
What's the best way?
I guess you'd want to use the GPU (layer animation right?) to avoid melting the cpu.
#IBDesignable class DottedVertical: UIView {
#IBInspectable var dotColor: UIColor = UIColor.faveColor
override func draw(_ rect: CGRect) {
// say you want 8 dots, with perfect fenceposting:
let totalCount = 8 + 8 - 1
let fullHeight = bounds.size.height
let width = bounds.size.width
let itemLength = fullHeight / CGFloat(totalCount)
let beginFromTop = !lowerHalfOnly ? 0.0 : (fullHeight * 8.0 / 15.0)
let top = CGPoint(x: width/2, y: beginFromTop)
let bottom = CGPoint(x: width/2, y: fullHeight)
let path = UIBezierPath()
path.move(to: top)
path.addLine(to: bottom)
path.lineWidth = width
let dashes: [CGFloat] = [itemLength, itemLength]
path.setLineDash(dashes, count: dashes.count, phase: 0)
dotColor.setStroke()
path.stroke()
}
(Bonus - if you had a few of these on screen, they'd have to be synced of course. There'd need to be a "sync" call that starts the running animation, so you can start them all at once with a notification or other message.)
Hate to answer my own question, here's a copy and paste solution based on the Men's suggestions above!
Good one! Superb effect...
#IBDesignable class DottedVertical: UIView {
#IBInspectable var dotColor: UIColor = sfBlack6 { didSet {setup()} }
override func layoutSubviews() { setup() }
var s:CAShapeLayer? = nil
func setup() {
// say you want 8 dots, with perfect fenceposting:
- calculate exactly as in the example in the question above -
// marching ants...
if (s == nil) {
s = CAShapeLayer()
self.layer.addSublayer(s!)
}
s!.strokeColor = dotColor.cgColor
s!.fillColor = backgroundColor?.cgColor
s!.lineWidth = width
let ns = NSNumber(value: Double(itemLength))
s!.lineDashPattern = [ns, ns]
let path = CGMutablePath()
path.addLines(between: [top, bottom])
s!.path = path
let anim = CABasicAnimation(keyPath: "lineDashPhase")
anim.fromValue = 0
anim.toValue = ns + ns
anim.duration = 1.75 // seconds
anim.repeatCount = Float.greatestFiniteMagnitude
s!.add(anim, forKey: nil)
self.layer.addSublayer(s!)
}
}
In my ios swift app I have SVG file - it's a shape of a map marker, now I want to draw it with animation. I managed to display the drawing thanks to the usage of pocketSVG https://github.com/pocketsvg/PocketSVG/ My code is as follows:
#IBOutlet weak var mainLogoView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "mainLogo", withExtension: "svg")!
//initialise a view that parses and renders an SVG file in the bundle:
let svgImageView = SVGImageView.init(contentsOf: url)
//scale the resulting image to fit the frame of the view, but
//maintain its aspect ratio:
svgImageView.contentMode = .scaleAspectFit
//layout the view:
svgImageView.translatesAutoresizingMaskIntoConstraints = false
mainLogoView.addSubview(svgImageView)
svgImageView.topAnchor.constraint(equalTo: mainLogoView.topAnchor).isActive = true
svgImageView.leftAnchor.constraint(equalTo: mainLogoView.leftAnchor).isActive = true
svgImageView.rightAnchor.constraint(equalTo: mainLogoView.rightAnchor).isActive = true
svgImageView.bottomAnchor.constraint(equalTo: mainLogoView.bottomAnchor).isActive = true
Timer.scheduledTimer(timeInterval: TimeInterval(2), target: self, selector: "functionHere", userInfo: nil, repeats: false)
}
func functionHere(){
self.performSegue(withIdentifier: "MainSegue", sender: nil)
}
So basically in my ViewController I added on storyboard a view called mainLogoView and then I'm displaying there the SVG file. Now, since it's a shaped marker, very similar to this: http://image.flaticon.com/icons/svg/116/116395.svg I want to draw it - during the time of 2 seconds I want to draw the shape around the circle.
How can I do it?
=====EDIT:
Following Josh's advice I commented out most of the code in my viewDidLoad and did instead:
let url = Bundle.main.url(forResource: "mainLogo", withExtension: "svg")!
for path in SVGBezierPath.pathsFromSVG(at: url)
{
var layer:CAShapeLayer = CAShapeLayer()
layer.path = path.cgPath
layer.lineWidth = 4
layer.strokeColor = orangeColor.cgColor
layer.fillColor = UIColor.white.cgColor
mainLogoView.addSubview(layer)
}
but now the last line throws an error
Cannot convert value of type 'CAShapeLayer' to expected argument type 'UIView'
Also, after editing my code - could you give me a hint how could I use Josh's method here?
Instead of using the imageView method convert your SVG into a cgPath. Assign this path to a CAShapeLayer and add that shape layer to your view. You can animate the CAShapeLayer's endStroke as follows:
func animateSVG(From startProportion: CGFloat, To endProportion: CGFloat, Duration duration: CFTimeInterval = animationDuration) {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = duration
animation.fromValue = startProportion
animation.toValue = endProportion
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
svgLayer.strokeEnd = endProportion
svgLayer.strokeStart = startProportion
svgLayer.add(animation, forKey: "animateRing")
}
I did encounter the same problem, this is my solution. svgWidth, svgHeight are width and height of svg tag
let url = Bundle.main.url(forResource: "mainLogo", withExtension: "svg")!
for path in SVGBezierPath.pathsFromSVG(at: url)
{
var layer:CAShapeLayer = CAShapeLayer()
layer.transform = CATransform3DMakeScale(CGFloat(mainLogoView.frame.width/svgWidth), CGFloat(mainLogoView.frame.height/svgHeight), 1)
layer.path = path.cgPath
layer.lineWidth = 4
layer.strokeColor = orangeColor.cgColor
layer.fillColor = UIColor.white.cgColor
layer.transform = CATransform3DMakeScale(2, 2, 1)
mainLogoView.layer.addSublayer(layer)
}
I want to create a custom UIView subclass representing a bunch of stars on a dark-blue sky.
Therefore, I created this view:
import UIKit
class ConstellationView: UIView {
// MARK: - Properties
#IBInspectable var numberOfStars: Int = 80
#IBInspectable var animated: Bool = false
// Private properties
private var starsToDraw = [CAShapeLayer]()
// Layers
private let starsLayer = CAShapeLayer()
// MARK: - Drawing
// override func drawRect(rect: CGRect) {
override func layoutSubviews() {
// Generate stars
drawStars(rect: self.bounds)
}
/// Generate stars
func drawStars(rect: CGRect) {
let width = rect.size.width
let height = rect.size.height
let screenBounds = UIScreen.main.bounds
// Create the stars and store them in starsToDraw array
for _ in 0 ..< numberOfStars {
let x = randomFloat() * width
let y = randomFloat() * height
// Calculate the thinness of the stars as a percentage of the screen resolution
let thin: CGFloat = max(screenBounds.width, screenBounds.height) * 0.003 * randomFloat()
let starLayer = CAShapeLayer()
starLayer.path = UIBezierPath(ovalIn: CGRect(x: x, y: y, width: thin, height: thin)).cgPath
starLayer.fillColor = UIColor.white.cgColor
starsToDraw.append(starLayer)
}
// Define a fade animation
let appearAnimation = CABasicAnimation(keyPath: "opacity")
appearAnimation.fromValue = 0.2
appearAnimation.toValue = 1
appearAnimation.duration = 1
appearAnimation.fillMode = kCAFillModeForwards
// Add the animation to each star (if animated)
for (index, star) in starsToDraw.enumerated() {
if animated {
// Add 1 s between each animation
appearAnimation.beginTime = CACurrentMediaTime() + TimeInterval(index)
star.add(appearAnimation, forKey: nil)
}
starsLayer.insertSublayer(star, at: 0)
}
// Add the stars layer to the view layer
layer.insertSublayer(starsLayer, at: 0)
}
private func randomFloat() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UINT32_MAX)
}
}
It works quite well, here is the result:
However, I'd like to have it animated, that is, each one of the 80 stars should appear one after the other, with a 1 second delay.
I tried to increase the beginTimeof my animation, but it does not seem to do the trick.
I checked with drawRect or layoutSubviews, but there is no difference.
Could you help me ?
Thanks
PS: to reproduce my app, just create a new single view app in XCode, create a new file with this code, and set the ViewController's view as a ConstellationView, with a dark background color. Also set the animated property to true, either in Interface Builder, or in the code.
PPS: this is in Swift 3, but I think it's still comprehensible :-)
You're really close, only two things to do!
First, you need to specify the key when you add the animation to the layer.
star.add(appearAnimation, forKey: "opacity")
Second, the fill mode for the animation needs to be kCAFillModeBackwards instead of kCAFillModeForwards.
For a more detailed reference see - https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreAnimation_guide/AdvancedAnimationTricks/AdvancedAnimationTricks.html
And here's a fun tutorial (for practice with CAAnimations!) - https://www.raywenderlich.com/102590/how-to-create-a-complex-loading-animation-in-swift
Hope this helps 😀
Full Code:
class ConstellationView: UIView {
// MARK: - Properties
#IBInspectable var numberOfStars: Int = 80
#IBInspectable var animated: Bool = true
// Private properties
private var starsToDraw = [CAShapeLayer]()
// Layers
private let starsLayer = CAShapeLayer()
override func awakeFromNib() {
super.awakeFromNib()
}
// MARK: - Drawing
override func layoutSubviews() {
// Generate stars
drawStars(rect: self.bounds)
}
/// Generate stars
func drawStars(rect: CGRect) {
let width = rect.size.width
let height = rect.size.height
let screenBounds = UIScreen.main.bounds
// Create the stars and store them in starsToDraw array
for _ in 0 ..< numberOfStars {
let x = randomFloat() * width
let y = randomFloat() * height
// Calculate the thinness of the stars as a percentage of the screen resolution
let thin: CGFloat = max(screenBounds.width, screenBounds.height) * 0.003 * randomFloat()
let starLayer = CAShapeLayer()
starLayer.path = UIBezierPath(ovalIn: CGRect(x: x, y: y, width: thin, height: thin)).cgPath
starLayer.fillColor = UIColor.white.cgColor
starsToDraw.append(starLayer)
}
// Define a fade animation
let appearAnimation = CABasicAnimation(keyPath: "opacity")
appearAnimation.fromValue = 0.2
appearAnimation.toValue = 1
appearAnimation.duration = 1
appearAnimation.fillMode = kCAFillModeBackwards
// Add the animation to each star (if animated)
for (index, star) in starsToDraw.enumerated() {
if animated {
// Add 1 s between each animation
appearAnimation.beginTime = CACurrentMediaTime() + TimeInterval(index)
star.add(appearAnimation, forKey: "opacity")
}
starsLayer.insertSublayer(star, above: nil)
}
// Add the stars layer to the view layer
layer.insertSublayer(starsLayer, above: nil)
}
private func randomFloat() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UINT32_MAX)
}
}
NO UIVIEW ANIMATIONS, I'M LEARNING CORE ANIMATION
When I run this code, the top image is not on the screen. Then 4 seconds later, it reappears and does as expected. Not sure why. What I want is for the top image to be on the screen when the app launches, and then 4 seconds later for the top image to move up and out of the screen.
#IBOutlet var top: UIImageView!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let openTop = CABasicAnimation(keyPath: "position.y")
openTop.fromValue = self.top.frame.origin.y
openTop.toValue = -self.view.bounds.size.height
openTop.duration = 1.0
openTop.beginTime = CACurrentMediaTime() + 4
self.top.layer.addAnimation(openTop, forKey: nil)
self.top.layer.position.y = -self.view.bounds.size.height
}
Any thoughts?
Here's what I came up with:
let l = top.layer!
let startingPosition = l.position
l.position = CGPointMake( CGRectGetMidX( self.view.bounds ), -l.frame.height * 0.5 )
l.addAnimation({
let anim = CABasicAnimation( keyPath: "position" )
anim.fromValue = NSValue( CGPoint:startingPosition )
anim.beginTime = CACurrentMediaTime() + 4.0
anim.fillMode = kCAFillModeBoth
return anim
}(), forKey: nil)
so you want the image to be on-screen at the start, and then 4 seconds later to fly off the top? You can do this by grouping animations together
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
// keep a track of where we want it to be
let y = self.top.layer.position.y
// move it out of the way - this where it will end up after the animation
self.top.layer.position.y = -self.view.bounds.size.height
// do nothing, other than display the image for 4 seconds
let doNothing = CABasicAnimation(keyPath: "position.y")
doNothing.fromValue = y
doNothing.toValue = y
doNothing.duration = 4.0
// zip it away
let openTop = CABasicAnimation(keyPath: "position.y")
openTop.fromValue = y
openTop.toValue = -self.view.bounds.size.height
openTop.duration = 1.0
openTop.beginTime = doNothing.beginTime + doNothing.duration
// create the group
let group = CAAnimationGroup()
group.duration = 5.01
group.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
group.removedOnCompletion = false
group.fillMode = kCAFillModeForwards
group.animations = [doNothing, openTop]
self.top.layer.addAnimation(group, forKey: nil)
}
I have two UIBezierPath...
First path shows the total path from to and fro destination and the second path is a copy of the first path but that copy should be a percentage of the first path which I am unable to do.
Basically I would like the plane to stop at the part where green UIBezier path ends and not go until the past green color.
I am attaching a video in hte link that will show the animation I am trying to get. http://cl.ly/302I3O2f0S3Y
Also a similar question asked is Move CALayer via UIBezierPath
Here is the relevant code
override func viewDidLoad() {
super.viewDidLoad()
let endPoint = CGPointMake(fullFlightLine.frame.origin.x + fullFlightLine.frame.size.width, fullFlightLine.frame.origin.y + 100)
self.layer = CALayer()
self.layer.contents = UIImage(named: "Plane")?.CGImage
self.layer.frame = CGRectMake(fullFlightLine.frame.origin.x - 10, fullFlightLine.frame.origin.y + 10, 120, 120)
self.path = UIBezierPath()
self.path.moveToPoint(CGPointMake(fullFlightLine.frame.origin.x, fullFlightLine.frame.origin.y + fullFlightLine.frame.size.height/4))
self.path.addQuadCurveToPoint(endPoint, controlPoint:CGPointMake(self.view.bounds.size.width/2, -200))
self.animationPath = self.path.copy() as! UIBezierPath
let w = (viewModel?.completePercentage) as CGFloat!
// let animationRectangle = UIBezierPath(rect: CGRectMake(fullFlightLine.frame.origin.x-20, fullFlightLine.frame.origin.y-270, fullFlightLine.frame.size.width*w, fullFlightLine.frame.size.height-20))
// let currentContext = UIGraphicsGetCurrentContext()
// CGContextSaveGState(currentContext)
// self.animationPath.appendPath(animationRectangle)
// self.animationPath.addClip()
// CGContextRestoreGState(currentContext)
self.shapeLayer = CAShapeLayer()
self.shapeLayer.path = path.CGPath
self.shapeLayer.strokeColor = UIColor.redColor().CGColor
self.shapeLayer.fillColor = UIColor.clearColor().CGColor
self.shapeLayer.lineWidth = 10
self.animationLayer = CAShapeLayer()
self.animationLayer.path = animationPath.CGPath
self.animationLayer.strokeColor = UIColor.greenColor().CGColor
self.animationLayer.strokeEnd = w
self.animationLayer.fillColor = UIColor.clearColor().CGColor
self.animationLayer.lineWidth = 3
fullFlightLine.layer.addSublayer(shapeLayer)
fullFlightLine.layer.addSublayer(animationLayer)
fullFlightLine.layer.addSublayer(self.layer)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
updateAnimationForPath(self.animationLayer)
}
func updateAnimationForPath(pathLayer : CAShapeLayer) {
let animation : CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position")
animation.path = pathLayer.path
animation.calculationMode = kCAAnimationPaced
animation.delegate = self
animation.duration = 3.0
self.layer.addAnimation(animation, forKey: "bezierPathAnimation")
}
}
extension Int {
var degreesToRadians : CGFloat {
return CGFloat(self) * CGFloat(M_PI) / 180.0
}
}
Your animation for traveling a path is exactly right. The only problem now is that you are setting the key path animation's path to the whole bezier path:
animation.path = pathLayer.path
If you want the animation to cover only part of that path, you have two choices:
Supply a shorter version of the bezier path, instead of pathLayer.path.
Alternatively, wrap the whole animation in a CAAnimationGroup with a shorter duration. For example, if your three-second animation is wrapped inside a two-second animation group, it will stop two-thirds of the way through.