CAShapeLayer strange behavior in the first time animation - ios

I've wrote this animation to the CAShapeLayer (pulseLayer) and in the viewDidLoad() :
let pulseLayer = CAShapeLayer()
#IBOutlet weak var btnCart: UIButton!
override func viewDidLoad() {
let longpress = UILongPressGestureRecognizer(target: self, action: #selector(CategoryViewController.longPressGestureRecognized(_:)))
tableView.addGestureRecognizer(longpress)
heartBeatAnimation.duration = 0.75
heartBeatAnimation.repeatCount = Float.infinity
heartBeatAnimation.autoreverses = true
heartBeatAnimation.fromValue = 1.0
heartBeatAnimation.toValue = 1.2
heartBeatAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
btnCart.layer.addSublayer(pulseLayer)
}
func addBtnCartLayerWithAnimation() {
let ovalPath = UIBezierPath(arcCenter: CGPoint(x: btnCart.frame.midX, y: btnCart.frame.midY), radius: btnCart.frame.width * 1.5, startAngle: 0*(CGFloat.pi / 180), endAngle: 360*(CGFloat.pi / 180), clockwise: true)
pulseLayer.path = ovalPath.cgPath
pulseLayer.opacity = 0.15
pulseLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
pulseLayer.bounds = ovalPath.cgPath.boundingBox
pulseLayer.add(heartBeatAnimation, forKey: "heartBeatAnimation")
pulseLayer.transform = CATransform3DScale(CATransform3DIdentity, 1.0, 1.0, 1.0)
}
and the removeLayer function is:
func removeLayer() {
pulseLayer.transform = CATransform3DScale(CATransform3DIdentity, 0.1, 0.1, 0.1)
pulseLayer.removeAllAnimations()
}
The problem is when the first animation of the layer is coming from the bottom of the view !
the first animation after viewDidLoad
then after that any invoke for this animation with start from the center(the defined anchor point)
any animation after the first one
Could anyone tell me why this happening ?
the whole class where I defined and used UILongGestureRecognizer on tableView to start/stop the animation :
func longPressGestureRecognized(_ gestureRecognizer: UIGestureRecognizer) {
let longPress = gestureRecognizer as! UILongPressGestureRecognizer
let state = longPress.state
let locationInView = longPress.location(in: tableView)
let indexPath = tableView.indexPathForRow(at: locationInView)
switch state {
case UIGestureRecognizerState.began:
if indexPath != nil {
addBtnCartLayerWithAnimation()
}
case UIGestureRecognizerState.changed:
// some code here not related to the animation
default:
removeLayer()
}
}

When using standalone layers (layers that are not the backing store of a UIView), implicit animations are added for every animatable property change.
You're seeing this effect because the layer is animating its properties from zero to the initial values you're setting in addBtnCartLayerWithAnimation().
What you want to do is to set these initial values without animation (which needs to be done explicitly). You can wrap the change in a transaction in which you disable animations like so:
CATransaction.begin()
CATransaction.setDisableActions(true)
pulseLayer.path = ovalPath.cgPath
pulseLayer.opacity = 0.15
pulseLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
pulseLayer.bounds = ovalPath.cgPath.boundingBox
pulseLayer.transform = CATransform3DScale(CATransform3DIdentity, 1.0, 1.0, 1.0)
CATransaction.commit()
pulseLayer.add(heartBeatAnimation, forKey: "heartBeatAnimation")

Related

Flip view like UIView.transition with Core Animation

I want to create a transition between two views like UIView.transition with .transitionFlipFromLeft. For example:
import UIKit
class ViewController: UIViewController {
static let frame = CGRect(x: 0, y: 0, width: 300, height: 200)
let viewContainer = UIView(frame: frame)
let view1 = UIView(frame: frame)
let view2 = UIView(frame: frame)
var currentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.view1.backgroundColor = .blue
self.view2.backgroundColor = .red
self.currentView = self.view1
self.view.addSubview(self.viewContainer)
self.viewContainer.addSubview(self.currentView)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if currentView == view1 {
flip(to: view2)
} else {
flip(to: view1)
}
}
func flip(to toView: UIView) {
UIView.transition(from: currentView,
to: toView,
duration: 1,
options: .transitionFlipFromLeft,
completion: { _ in self.currentView = toView })
}
}
It should be possible to reach a similar effect by using Core Animation. I replaced UIView.transition in func flip(to toView: UIView):
func flip(to toView: UIView) {
var transform = CATransform3DIdentity
transform.m34 = -1 / 400
toView.layer.transform = transform
self.currentView.layer.transform = transform
let disappearByRotating = CABasicAnimation(keyPath: "transform.rotation.y")
disappearByRotating.duration = 0.5
disappearByRotating.fromValue = 0
disappearByRotating.toValue = CGFloat.pi / 2
let appearByRotating = CABasicAnimation(keyPath: "transform.rotation.y")
appearByRotating.duration = 0.5
appearByRotating.fromValue = CGFloat.pi / 2
appearByRotating.toValue = CGFloat.pi
CATransaction.begin()
CATransaction.setCompletionBlock {
self.currentView.removeFromSuperview()
self.viewContainer.addSubview(toView) // <= Problem!
toView.layer.add(appearByRotating, forKey: "appear")
self.currentView = toView
}
self.currentView.layer.add(disappearByRotating, forKey: "disappear")
CATransaction.commit()
}
I used two animations: In the first animation, the first view rotates from the left to the middle, in the second animation, the second view rotates from the middle to the right.
When I add the second view to my viewContainer, it is displayed untransformed before the second animation starts. This causes flickering:
How can I prevent the flickering?
One option:
apply a 90-degree rotation to toView.layer before anything else
toView will now be "invisible" so add it as a subview
embed a new CATransaction with new Completion Block in the original Completion Block to "remove" the transform from toView.layer
Try this:
func flip(to toView: UIView) {
var transform = CATransform3DIdentity
transform.m34 = -1 / 400
// start toView rotated 90 degrees
transform = CATransform3DRotate(transform, CGFloat.pi / 2, 0, 1, 0)
toView.layer.transform = transform
// because toView's layer is rotated 90 degrees, we can
// add the subview here and it won't be visible
// really no difference between .addSubview and .insertSubview for our purposes
// but we'll insert it under the current view anyway
self.viewContainer.insertSubview(toView, belowSubview: self.currentView)
transform = CATransform3DIdentity
transform.m34 = -1 / 400
self.currentView.layer.transform = transform
let disappearByRotating = CABasicAnimation(keyPath: "transform.rotation.y")
disappearByRotating.duration = 0.5
disappearByRotating.fromValue = 0
disappearByRotating.toValue = CGFloat.pi / 2
disappearByRotating.fillMode = .forwards
disappearByRotating.isRemovedOnCompletion = false
let appearByRotating = CABasicAnimation(keyPath: "transform.rotation.y")
appearByRotating.duration = 0.5
appearByRotating.fromValue = -CGFloat.pi / 2
appearByRotating.toValue = 0
appearByRotating.fillMode = .forwards
appearByRotating.isRemovedOnCompletion = false
CATransaction.begin()
CATransaction.setCompletionBlock {
self.currentView.removeFromSuperview()
// start a new CATransaction with new Completion Block
CATransaction.begin()
CATransaction.setCompletionBlock {
self.currentView.layer.removeAnimation(forKey: "disappear")
toView.layer.removeAnimation(forKey: "appear")
// remove 90-degree-rotation starting point from toView
toView.layer.transform = CATransform3DIdentity
self.currentView = toView
}
toView.layer.add(appearByRotating, forKey: "appear")
CATransaction.commit()
}
self.currentView.layer.add(disappearByRotating, forKey: "disappear")
CATransaction.commit()
}

How to create a flashing pointer effect to UIImages in Swift

I'm trying to create a pointer effect in Swift. I have six UIImageView each has a UIImage that are ordered in a circular way. I want to create an animation of having each image flash (as if it's a pointer indication) for a certain duration.
I thought of creating an array with a transparent version of the images and then create an animated sequence from them but the duration gets mixed up.
This is the idea I'm trying to achieve. I want the images to kind of have this flashing effect, one by one.
This is how I accomplished placing views in a circle and making them "flash"..
First I created regular views (I didn't want to use ImageView's but you are okay to change the code however you like)..
I calculated the angle at which the views need to be placed around a centre point with some radius.. to get them to place in a circle.
Next I create an animation function which has both a forward and reverse animation (I couldn't get autoreverses flag to work)..
To get one to display after the other, I simply add a delay (x2 because forward + reverse)..
To figure out when ALL animations have completed, I wrapped the entire function in a CATransaction.
Note: If you don't need the circular placement code, simply remove it. AFAIK, you only need the animation code.
//
// ViewController.swift
// TestSO
//
// Created by Brandon on 2018-03-03.
// Copyright © 2018 XIO. All rights reserved.
//
import UIKit
extension UIColor {
class func random() -> UIColor {
let rand = { (max: CGFloat) -> CGFloat in
let rnd = CGFloat(arc4random()) / CGFloat(UInt32.max)
return rnd * max
}
return UIColor(red: rand(1.0), green: rand(1.0), blue: rand(1.0), alpha: 1.0)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let makeView = { () -> UIView in
let view = UIView()
view.backgroundColor = UIColor.random()
view.frame = CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0)
self.view.addSubview(view)
return view
}
let imageViews = [
makeView(),
makeView(),
makeView(),
makeView(),
makeView(),
makeView()
]
let locationForView = { (angle: CGFloat, center: CGPoint, radius: CGFloat) -> CGPoint in
let angle = angle * CGFloat.pi / 180.0
return CGPoint(x: center.x - radius * cos(angle), y: center.y + radius * sin(angle))
}
for i in 0..<imageViews.count {
let center = self.view.center
let radius = ((150.0 + imageViews[i].bounds.size.width) / 2.0)
let count = imageViews.count
imageViews[i].center = locationForView(((360.0 / CGFloat(count)) * CGFloat(i)) + 90.0, center, radius)
}
self.animate(views: imageViews.reversed(), duration: 3.0, intervalDelay: 0.5)
}
private func animate(views: [UIView], duration: TimeInterval, intervalDelay: TimeInterval) {
CATransaction.begin()
CATransaction.setCompletionBlock {
print("COMPLETED ALL ANIMATIONS")
}
var delay: TimeInterval = 0.0
let interval = duration / TimeInterval(views.count)
for view in views {
let colour = view.backgroundColor
let transform = view.transform
UIView.animate(withDuration: interval, delay: delay, options: [.curveEaseIn], animations: {
view.backgroundColor = UIColor.red
view.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}, completion: { (finished) in
UIView.animate(withDuration: interval, delay: 0.0, options: [.curveEaseIn], animations: {
view.backgroundColor = colour
view.transform = transform
}, completion: { (finished) in
})
})
delay += (interval * 2.0) + intervalDelay
}
CATransaction.commit()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Core Animation - modify animation property

I have animation
func startRotate360() {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = Double.pi * 2
rotation.duration = 1
rotation.isCumulative = true
rotation.repeatCount = Float.greatestFiniteMagnitude
self.layer.add(rotation, forKey: "rotationAnimation")
}
What I want is ability to stop animation by setting its repeat count to 1, so it completes current rotation (simply remove animation is not ok because it looks not good)
I try following
func stopRotate360() {
self.layer.animation(forKey: "rotationAnimation")?.repeatCount = 1
}
But I get crash and in console
attempting to modify read-only animation
How to access writable properties ?
Give this a go. You can in fact change CAAnimations that are in progress. There are so many ways. This is the fastest/simplest. You could even stop the animation completely and resume it without the user even noticing.
You can see the start animation function along with the stop. The start animation looks similar to yours while the stop grabs the current rotation from the presentation layer and creates an animation to rotate until complete. I also smoothed out the duration to be a percentage of the time needed to complete based on current rotation z to full rotation based on the running animation. Then I remove the animation with the repeat count and add the new animation. You can see the view rotate smoothly to the final position and stop. You will get the idea. Drop it in and run it and see what you think. Hit the button to start and hit it again to see it finish rotation and stop.
import UIKit
class ViewController: UIViewController {
var animationView = UIView()
var button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
animationView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
animationView.backgroundColor = .green
animationView.center = view.center
self.view.addSubview(animationView)
let label = UILabel(frame: animationView.bounds)
label.text = "I Spin"
animationView.addSubview(label)
button = UIButton(frame: CGRect(x: 20, y: animationView.frame.maxY + 60, width: view.bounds.width - 40, height: 40))
button.setTitle("Animate", for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(self, action: #selector(ViewController.pressed), for: .touchUpInside)
self.view.addSubview(button)
}
func pressed(){
if let title = button.titleLabel?.text{
let trans = CATransition()
trans.type = "rippleEffect"
trans.duration = 0.6
button.layer.add(trans, forKey: nil)
switch title {
case "Animate":
//perform animation
button.setTitle("Stop And Finish", for: .normal)
rotateAnimationRepeat()
break
default:
//stop and finish
button.setTitle("Animate", for: .normal)
stopAnimationAndFinish()
break
}
}
}
func rotateAnimationRepeat(){
//just to be sure because of how i did the project
animationView.layer.removeAllAnimations()
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = Double.pi * 2
rotation.duration = 0.5
rotation.repeatCount = Float.greatestFiniteMagnitude
//not doing cumlative
animationView.layer.add(rotation, forKey: "rotationAnimation")
}
func stopAnimationAndFinish(){
if let presentation = animationView.layer.presentation(){
if let currentRotation = presentation.value(forKeyPath: "transform.rotation.z") as? CGFloat{
var duration = 0.5
//smooth out duration for change
duration = Double((CGFloat(Double.pi * 2) - currentRotation))/(Double.pi * 2)
animationView.layer.removeAllAnimations()
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = currentRotation
rotation.toValue = Double.pi * 2
rotation.duration = duration * 0.5
animationView.layer.add(rotation, forKey: "rotationAnimation")
}
}
}
}
Result:
2019 typical modern syntax
Setup the arc and the layer like this:
import Foundation
import UIKit
class RoundChaser: UIView {
private let lineThick: CGFloat = 10.0
private let beginFraction: CGFloat = 0.15
// where does the arc drawing begin?
// 0==top, .25==right, .5==bottom, .75==left
private lazy var arcPath: CGPath = {
let b = beginFraction * .pi * 2.0
return UIBezierPath(
arcCenter: bounds.centerOfCGRect(),
radius: bounds.width / 2.0 - lineThick / 2.0,
startAngle: .pi * -0.5 + b,
// recall that .pi * -0.5 is the "top"
endAngle: .pi * 1.5 + b,
clockwise: true
).cgPath
}()
private lazy var arcLayer: CAShapeLayer = {
let l = CAShapeLayer()
l.path = arcPath
l.fillColor = UIColor.clear.cgColor
l.strokeColor = UIColor.purple.cgColor
l.lineWidth = lineThick
l.lineCap = CAShapeLayerLineCap.round
l.strokeStart = 0
l.strokeEnd = 0
// if both are same, it is hidden. initially hidden
layer.addSublayer(l)
return l
}()
then initialization is this easy
open override func layoutSubviews() {
super.layoutSubviews()
arcLayer.frame = bounds
}
finally animation is easy
public func begin() {
CATransaction.begin()
let e : CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
e.duration = 2.0
e.fromValue = 0
e.toValue = 1.0
// recall 0 will be our beginFraction, see above
e.repeatCount = .greatestFiniteMagnitude
self.arcLayer.add(e, forKey: nil)
CATransaction.commit()
}
}
Maybe this is not the best solution but it works, as you say you can not modify properties of the CABasicAnimation once is created, also we need to remove the rotation.repeatCount = Float.greatestFiniteMagnitude, if notCAAnimationDelegatemethodanimationDidStop` is never called, with this approach the animation can be stoped without any problems as you need
step 1: first declare a variable flag to mark as you need stop animation in your custom class
var needStop : Bool = false
step 2: add a method to stopAnimation after ends
func stopAnimation()
{
self.needStop = true
}
step 3: add a method to get your custom animation
func getRotate360Animation() ->CAAnimation{
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = Double.pi * 2
rotation.duration = 1
rotation.isCumulative = true
rotation.isRemovedOnCompletion = false
return rotation
}
step 4: Modify your startRotate360 func to use your getRotate360Animation() method
func startRotate360() {
let rotationAnimation = self.getRotate360Animation()
rotationAnimation.delegate = self
self.layer.add(rotationAnimation, forKey: "rotationAnimation")
}
step 5: Implement CAAnimationDelegate in your class
extension YOURCLASS : CAAnimationDelegate
{
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if(anim == self.layer?.animation(forKey: "rotationAnimation"))
{
self.layer?.removeAnimation(forKey: "rotationAnimation")
if(!self.needStop){
let animation = self.getRotate360Animation()
animation.delegate = self
self.layer?.add(animation, forKey: "rotationAnimation")
}
}
}
}
This works and was tested
Hope this helps you

Can't get good performance with Draw(_ rect: CGRect)

I have a Timer() that asks the view to refresh every x seconds:
func updateTimer(_ stopwatch: Stopwatch) {
stopwatch.counter = stopwatch.counter + 0.035
Stopwatch.circlePercentage += 0.035
stopwatchViewOutlet.setNeedsDisplay()
}
--
class StopwatchView: UIView, UIGestureRecognizerDelegate {
let buttonClick = UITapGestureRecognizer()
override func draw(_ rect: CGRect) {
Stopwatch.drawStopwatchFor(view: self, gestureRecognizers: buttonClick)
}
}
--
extension Stopwatch {
static func drawStopwatchFor(view: UIView, gestureRecognizers: UITapGestureRecognizer) {
let scale: CGFloat = 0.8
let joltButtonView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 75, height: 75))
let imageView: UIImageView!
// -- Need to hook this to the actual timer --
let temporaryVariableForTimeIncrement = CGFloat(circlePercentage)
// Exterior of sphere:
let timerRadius = min(view.bounds.size.width, view.bounds.size.height) / 2 * scale
let timerCenter = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
let path = UIBezierPath(arcCenter: timerCenter, radius: timerRadius, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
path.lineWidth = 2.0
UIColor.blue.setStroke()
path.stroke()
// Interior of sphere
let startAngle = -CGFloat.pi / 2
let arc = CGFloat.pi * 2 * temporaryVariableForTimeIncrement / 100
let cPath = UIBezierPath()
cPath.move(to: timerCenter)
cPath.addLine(to: CGPoint(x: timerCenter.x + timerRadius * cos(startAngle), y: timerCenter.y))
cPath.addArc(withCenter: timerCenter, radius: timerRadius * CGFloat(0.99), startAngle: startAngle, endAngle: arc + startAngle, clockwise: true)
cPath.addLine(to: CGPoint(x: timerCenter.x, y: timerCenter.y))
let circleShape = CAShapeLayer()
circleShape.path = cPath.cgPath
circleShape.fillColor = UIColor.cyan.cgColor
view.layer.addSublayer(circleShape)
// Jolt button
joltButtonView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
joltButtonView.layer.cornerRadius = 38
joltButtonView.backgroundColor = UIColor.white
imageView = UIImageView(frame: joltButtonView.frame)
imageView.contentMode = .scaleAspectFit
imageView.image = image
joltButtonView.addGestureRecognizer(gestureRecognizers)
view.addSubview(joltButtonView)
view.addSubview(imageView)
}
}
My first problem is that the subviews are getting redrawn each time. The second one is that after a couple seconds, the performance starts to deteriorate really fast.
Too many instances of the subview
Trying to drive the blue graphic with a Timer()
Should I try to animate the circle percentage graphic instead of redrawing it each time the timer function is called?
The major observation is that you should not be adding subviews in draw. That is intended for rendering a single frame and you shouldn't be adding/removing things from the view hierarchy inside draw. Because you're adding subviews roughly ever 0.035 seconds, your view hierarchy is going to explode, with adverse memory and performance impact.
You should either have a draw method that merely calls stroke on your updated UIBezierPath for the seconds hand. Or, alternatively, if using CAShapeLayer, just update its path (and no draw method is needed at all).
So, a couple of peripheral observations:
You are incrementing your "percentage" for every tick of your timer. But you are not guaranteed the frequency with which your timer will be called. So, instead of incrementing some "percentage", you should save the start time when you start the timer, and then upon every tick of the timer, you should recalculate the amount of time elapsed between then and now when figuring out how much time has elapsed.
You are using a Timer which is good for most purposes, but for the sake of optimal drawing, you really should use a CADisplayLink, which is optimally timed to allow you to do whatever you need before the next refresh of the screen.
So, here is an example of a simple clock face with a sweeping second hand:
open class StopWatchView: UIView {
let faceLineWidth: CGFloat = 5 // LineWidth of the face
private var startTime: Date? { didSet { self.updateHand() } } // When was the stopwatch resumed
private var oldElapsed: TimeInterval? { didSet { self.updateHand() } } // How much time when stopwatch paused
public var elapsed: TimeInterval { // How much total time on stopwatch
guard let startTime = startTime else { return oldElapsed ?? 0 }
return Date().timeIntervalSince(startTime) + (oldElapsed ?? 0)
}
private weak var displayLink: CADisplayLink? // Display link animating second hand
public var isRunning: Bool { return displayLink != nil } // Is the timer running?
private var clockCenter: CGPoint { // Center of the clock face
return CGPoint(x: bounds.midX, y: bounds.midY)
}
private var radius: CGFloat { // Radius of the clock face
return (min(bounds.width, bounds.height) - faceLineWidth) / 2
}
private lazy var face: CAShapeLayer = { // Shape layer for clock face
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = self.faceLineWidth
shapeLayer.strokeColor = #colorLiteral(red: 0.1215686277, green: 0.01176470611, blue: 0.4235294163, alpha: 1).cgColor
shapeLayer.fillColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0).cgColor
return shapeLayer
}()
private lazy var hand: CAShapeLayer = { // Shape layer for second hand
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 3
shapeLayer.strokeColor = #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1).cgColor
shapeLayer.fillColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0).cgColor
return shapeLayer
}()
override public init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
// add necessary shape layers to layer hierarchy
private func configure() {
layer.addSublayer(face)
layer.addSublayer(hand)
}
// if laying out subviews, make sure to resize face and update hand
override open func layoutSubviews() {
super.layoutSubviews()
updateFace()
updateHand()
}
// stop display link when view disappears
//
// this prevents display link from keeping strong reference to view after view is removed
override open func willMove(toSuperview newSuperview: UIView?) {
if newSuperview == nil {
pause()
}
}
// MARK: - DisplayLink routines
/// Start display link
open func resume() {
// cancel any existing display link, if any
pause()
// start new display link
startTime = Date()
let displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink(_:)))
displayLink.add(to: .main, forMode: .commonModes)
// save reference to it
self.displayLink = displayLink
}
/// Stop display link
open func pause() {
displayLink?.invalidate()
// calculate floating point number of seconds
oldElapsed = elapsed
startTime = nil
}
open func reset() {
pause()
oldElapsed = nil
}
/// Display link handler
///
/// Will update path of second hand.
#objc func handleDisplayLink(_ displayLink: CADisplayLink) {
updateHand()
}
/// Update path of clock face
private func updateFace() {
face.path = UIBezierPath(arcCenter: clockCenter, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true).cgPath
}
/// Update path of second hand
private func updateHand() {
// convert seconds to an angle (in radians) and figure out end point of seconds hand on the basis of that
let angle = CGFloat(elapsed / 60 * 2 * .pi - .pi / 2)
let endPoint = CGPoint(x: clockCenter.x + cos(angle) * radius * 0.9, y: clockCenter.y + sin(angle) * radius * 0.9)
// update path of hand
let path = UIBezierPath()
path.move(to: clockCenter)
path.addLine(to: endPoint)
hand.path = path.cgPath
}
}
And
class ViewController: UIViewController {
#IBOutlet weak var stopWatchView: StopWatchView!
#IBAction func didTapStartStopButton () {
if stopWatchView.isRunning {
stopWatchView.pause()
} else {
stopWatchView.resume()
}
}
#IBAction func didTapResetButton () {
stopWatchView.reset()
}
}
Now, in the above example, I'm just updating the CAShapeLayer of the seconds hand in my CADisplayLink handler. Like I said at the start, you can alternatively have a draw method that simply strokes the paths you need for single frame of animation and then call setNeedsDisplay in your display link handler. But if you do that, don't change the view hierarchy within draw, but rather do any configuration you need in init and draw should just stroke whatever the path should be at that moment.

How can I move an image in Swift?

I would like to be able to move an object (in my case, an image "puppy") up 1 pixel every time a button is pressed. I've stumbled upon old Objective-C solutions as well as Swift code that was similar, but none that fit my specific problem. I would love to know an easy way to move my image. This is my code so far from what I could gather(I'm hoping it's unnecessarily long and can be reduced to a line or two):
#IBAction func tapButton() {
UIView.animateWithDuration(0.75, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {
self.puppy.alpha = 1
self.puppy.center.y = 0
}, completion: nil)
var toPoint: CGPoint = CGPointMake(0.0, 1.0)
var fromPoint : CGPoint = CGPointZero
var movement = CABasicAnimation(keyPath: "movement")
movement.additive = true
movement.fromValue = NSValue(CGPoint: fromPoint)
movement.toValue = NSValue(CGPoint: toPoint)
movement.duration = 0.3
view.layer.addAnimation(movement, forKey: "move")
}
This way you can change a position of your imageView
#IBAction func tapButton() {
UIView.animateWithDuration(0.75, delay: 0, options: .CurveLinear, animations: {
// this will change Y position of your imageView center
// by 1 every time you press button
self.puppy.center.y -= 1
}, completion: nil)
}
And remove all other code from your button action.
CATransaction.begin()
CATransaction.setCompletionBlock { () -> Void in
self.viewBall.layer.position = self.viewBall.layer.presentationLayer().position
}
var animation = CABasicAnimation(keyPath: "position")
animation.duration = ballMoveTime
var currentPosition : CGPoint = viewBall.layer.presentationLayer().position
animation.fromValue = NSValue(currentPosition)
animation.toValue = NSValue(CGPoint: CGPointMake(currentPosition.x, (currentPosition.y + 1)))
animation.removedOnCompletion = false
animation.fillMode = kCAFillModeForwards
viewBall.layer.addAnimation(animation, forKey: "transform")
CATransaction.commit()
Replace viewBall to your image object
And also remove completion block if you don't want.
You can do this.
func clickButton() {
UIView.animateWithDuration(animationDuration, animations: {
let buttonFrame = self.button.frame
buttonFrame.origin.y = buttonFrame.origin.y - 1.0
self.button.frame = buttonFrame
}
}

Resources