Search code examples
iosswiftanimationswiftycam

Create animation for tap to focus using SwiftyCams didFocusAtPoint function


I am using SwiftyCam and would like to give some sort of animated feedback when using the tap to focus feature.

SwiftyCam comes with a didFocusAtPoint function which is called when the screen is tapped and provides you with the point of the tap.

How can I now create and show an animation at that point?

func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFocusAtPoint point: CGPoint) {
     // Called when a user initiates a tap gesture on the preview layer
     // Will only be called if tapToFocus = true
     // Returns a CGPoint of the tap location on the preview layer
}

Solution

  • The DemoSwiftyCam project on Github already has an implementation for this feature:

    ViewController.swift

    func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFocusAtPoint point: CGPoint) {
        print("Did focus at point: \(point)")
        focusAnimationAt(point)
    }
    

    ...

    extension ViewController {
    
    ///...
    
    
    fileprivate func focusAnimationAt(_ point: CGPoint) {
        let focusView = UIImageView(image: #imageLiteral(resourceName: "focus")) // Image Available in DemoSwiftyCam Assets.xcassets
        focusView.center = point
        focusView.alpha = 0.0
        view.addSubview(focusView)
    
        UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
            focusView.alpha = 1.0
            focusView.transform = CGAffineTransform(scaleX: 1.25, y: 1.25)
        }) { (success) in
            UIView.animate(withDuration: 0.15, delay: 0.5, options: .curveEaseInOut, animations: {
                focusView.alpha = 0.0
                focusView.transform = CGAffineTransform(translationX: 0.6, y: 0.6)
            }) { (success) in
                focusView.removeFromSuperview()
            }
        }
    }