Swift interpolation for gesture-driven animations

Overview

Interpolate - Swift interpolation for gesture-driven animations

Platforms Build Status Version Carthage compatible

Interpolate

Interpolate is a powerful Swift interpolation framework for creating interactive gesture-driven animations.

Usage

The 🔑 idea of Interpolate is - all animation is the interpolation of values over time.

To use Interpolate:

Import Interpolate at the top of your Swift file.

import Interpolate

Create an Interpolate object with a from value, a to value and an apply closure that applies the interpolation's result to the target object.

let colorChange = Interpolate(from: UIColor.white,
to: UIColor.red,
apply: { [weak self] (color) in
    self?.view.backgroundColor = color
})

Alternatively, you can specify multiple values for the interpolation in an array. The Swift compiler might have issues to infer the type of the array so it's best to be explicit.

let colors: [UIColor] = [UIColor.white, UIColor.red, UIColor.green]
let colorChange = Interpolate(values: colors,
apply: { [weak self] (color) in
    self?.view.backgroundColor = color
})

Next, you will need to define a way to translate your chosen gesture's progress to a percentage value (i.e. a CGFloat between 0.0 and 1.0).

For a gesture recognizer or delegate that reports every step of its progress (e.g. UIPanGestureRecognizer or a ScrollViewDidScroll) you can just apply the percentage directly to the Interpolate object:

@IBAction func handlePan(recognizer: UIPanGestureRecognizer) {
    let translation = recognizer.translation(in: self.view)
    let translatedCenterY = view.center.y + translation.y
    let progress = translatedCenterY / self.view.bounds.size.height
    colorChange.progress = progress
}

For other types of gesture recognizers that only report a beginning and an end (e.g. a UILongPressGestureRecognizer), you can animate directly to a target progress value with a given duration. For example:

@IBAction func handleLongPress(recognizer: UILongPressGestureRecognizer) {
    switch recognizer.state {
        case .began:
            colorChange.animate(1.0, duration: 0.3)
        case .cancelled, .ended, .failed:
            colorChange.animate(0.0, duration: 0.3)
        default: break
    }
}

To stop an animation:

colorChange.stopAnimation()

When you are done with the interpolation altogether:

colorChange.invalidate()

Voila!

What can I interpolate?

Interpolate currently supports the interpolation of:

  • CGPoint
  • CGRect
  • CGSize
  • Double
  • CGFloat
  • Int
  • NSNumber
  • UIColor
  • CGAffineTransform
  • CATransform3D
  • UIEdgeInsets

More types will be added over time.

Advanced usage

Interpolate is not just for dull linear interpolations.

For smoother animations, consider using any of the following functions: easeIn, easeOut, easeInOut and Spring.

// Spring interpolation
let shadowPosition = Interpolate(from: -shadowView.frame.size.width,
to: (self.view.bounds.size.width - shadowView.frame.size.width)/2,
function: SpringInterpolation(damping: 30.0, velocity: 0.0, mass: 1.0, stiffness: 100.0),
apply: { [weak self] (originX) in
    self?.shadowView.frame.origin.x = originX
})

// Ease out interpolation
let groundPosition = Interpolate(from: CGPoint(x: 0, y: self.view.bounds.size.height),
to: CGPoint(x: 0, y: self.view.bounds.size.height - 150),
function: BasicInterpolation.easeOut,
apply: { [weak self] (origin) in
    self?.groundView.frame.origin = origin
})

In fact, you can easily create and use your own interpolation function - all you need is an object that conforms to the InterpolationFunction protocol.

Setting up with CocoaPods

source 'https://github.com/CocoaPods/Specs.git'
pod 'Interpolate', '~> 1.3.0'

Setting up with Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate Interpolate into your Xcode project using Carthage, specify it in your Cartfile:

github "marmelroy/Interpolate"

Inspiration

Comments
  • Mid Vector

    Mid Vector

    I was hoping Interpolate could make my life a lot easier with my current task. I have 3 screens inside a UIScrollView So three pages. Each pages is a specific color. I need to animate the background color as I scroll. It seems that interpolate only allows two vectors. To and From I need to define a third: Mid. So if progress was at 0 then the screen would be blue. progress was set to 0.5 the screen would be red progress set to 1 would be green.

    Is this possible with the current version?

    opened by bryan1anderson 3
  • Interpolating a ProgressView from top to Bottom leads to Fuzzy UI Object

    Interpolating a ProgressView from top to Bottom leads to Fuzzy UI Object

    @marmelroy I tried this all day yesterday with the JWGCircleCounter) and CircleProgressView

    Steps to Reproduce

    • Instantiate a CircleProgressView or any other animatable circle view to the top right of your view.

    • On tap, interpolate the object down to the center bottom of the screen.

    • The object on top right will be perfectly nice and crisp.

    • When it gets to the bottom, it will be blury and fuzzy

    class ViewController: UIViewController {
        
        var circle: CircleProgressView!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            self.addRecordButton()
        }
        
        func addRecordButton() {
            self.circle = CircleProgressView(x: self.view.size.width - 56, y: 29, w: 30, h: 30)
            self.circle.trackBackgroundColor = .blue
            self.circle.trackBorderWidth = 3
            self.circle.backgroundColor = .clear
            self.circle.layer.cornerRadius = self.circle.size.width / 2
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(self.tap))
            self.circle.addGestureRecognizer(tap)
            
            self.view.addSubview(circle)
        }
        
        func tap() {
            self.interpolate()
        }
        
        func interpolate() {
            let newframe = CGRect(x: self.view.centerX - 37.5, y: self.view.size.height - 100, w: 75, h: 75)
            let interpolate = Interpolate(from: self.circle.frame, to: newframe) { (newframe) in
                self.circle.frame = newframe
            }
            interpolate.animate(duration: 5)
        }
    }
    
    opened by otymartin 2
  • Interpolate not working

    Interpolate not working

    Hi ! :) I have the problem that my code below is not printing any values. I'm using Xcode 8 and Swift 3.

    
    let i = Interpolate(from: 100.0, to: 3.0, apply: { n in print(n) })
            i.animate(duration: 3.0)
    
    opened by BilalReffas 2
  • Interpolate not running with Double values

    Interpolate not running with Double values

    For some reason, the following doesn't work at all:

    let i = Interpolate(from: 100.0, to: 3.0, apply: { n in print(n) })
    i.animate(duration: 3.0)
    

    but this does:

    i = Interpolate(from: CGFloat(100.0), to: CGFloat(3.0), apply: { n in print(n) })
    i.animate(duration: 3.0)
    

    I'm using version 0.2.0 with Swift 2.3. I can't figure this out without getting pretty deep into the code but the init() seems to set up the instance variables identically. I'm lost, but I'd love to know what the problem is — hopefully on my end.

    opened by wafisher 2
  • Use swift_version instead of xcode overrides

    Use swift_version instead of xcode overrides

    Cocoapods supports setting the swift version directly using the swift_version configuration parameter.

    I was working on a project that used Interpolate but I was getting weird compiler errors about code that was recently updated for Swift 4.2. It turns out the xcconfig for the swift version wasn't getting properly set on the Pod target. Once I changed that setting to use swift_version the target built without errors.

    opened by farktronix 1
  • SpringInterpolation does not complete

    SpringInterpolation does not complete

    @marmelroy eg. SpringInterpolation(damping: 30.0, velocity: 0.0, mass: 1.0, stiffness: 100.0) Hey, I find that using Spring Interpolations, my animations do not finish at their destination even though progress = 100%. Instead they are always near completion.

    Why is that?

    opened by otymartin 1
  • App extension safe API

    App extension safe API

    I use this project in an App extension and always got the warning that this library isn't App extension safe. Since the code doesn't reference any non App Extension safe APIs, it is safe to enable this.

    I also updated the project settings to the recommended settings in Xcode 8.1

    opened by leoMehlig 1
  • animating constraints

    animating constraints

    Is there also a way to animate constraints with Interpolate? Would be nice to have an example for that.

    I assume it's just calling layoutIfNeeded() after assigning the change inside Interpolate closure?

    opened by tcurdt 1
  • start multiple animations at the same time

    start multiple animations at the same time

    The example app has basically

        func progress(scrollProgress:CGFloat) {
            let groundProgress = scrollProgress * 1.5
            backgroundColorChange?.progress = scrollProgress
            logoAlpha?.progress = scrollProgress
            groundPosition?.progress = groundProgress
            bojackPosition?.progress = groundProgress
            bojackShadowPosition?.progress = max(groundProgress - 1, 0)
        }
    

    So I can set the progress with procress(0) and procress(1) for the whole interpolations - but how I can animate that? Running animate on all interpolations feels wrong. Something along the lines of this would be great:

    progress(0)
    UIView.animate(...) {
      progress(1)
    }
    
    opened by tcurdt 1
  • Sample Podfile

    Sample Podfile

    • Updates the Sample Podfile to work with CocoaPods 1.0.
    • Adds the missing files to git, that are create after a pod install. This makes a pod install redundant and one can try the Sample right away after the download.
    opened by leoMehlig 1
  • Interpolate generic initializer

    Interpolate generic initializer

    Use generic initializer to create Interpolate objects. This way, there is no need to typecast inside the apply block, so the code becomes cleaner.

    let colorChange = Interpolate(from: UIColor.whiteColor(), to: UIColor.redColor(), apply: { [weak self] (color) in
        self?.view.backgroundColor = color
    })
    

    Also, this guarantees that the type of from parameter is the same as the type of to, so there is no way to write code like this:

    let change = Interpolate(from: UIColor.whiteColor(), to: 10.0, apply: { [weak self] (result) in
        // This will cause a fatal error in calculateDiff
    })
    
    opened by romanroibu 1
Releases(1.2.0)
Owner
Roy Marmelstein
Ya tu sabes.
Roy Marmelstein
A Swift library to take the power of UIView.animateWithDuration(_:, animations:...) to a whole new level - layers, springs, chain-able animations and mixing view and layer animations together!

ver 2.0 NB! Breaking changes in 2.0 - due to a lot of requests EasyAnimation does NOT automatically install itself when imported. You need to enable i

Marin Todorov 3k Dec 27, 2022
Simple, extensible interpolation framework

THIS PROJECT IS NO LONGER MAINTAINED. Popsicle is a Swift framework for creating and managing interpolations of different value types with built-in UI

David Roman 1.1k Nov 17, 2022
Ease is an event driven animation system that combines the observer pattern with custom spring animations as observers

Ease is an event driven animation system that combines the observer pattern with custom spring animations as observers. It's magic. Features Animate a

Robert-Hein Hooijmans 1.3k Nov 17, 2022
A collection of animations for iOS. Simple, just add water animations.

DCAnimationKit A collection of animations for iOS Simply, just add water! DCAnimationKit is a category on UIView to make animations easy to perform. E

Dalton 797 Sep 23, 2022
(Animate CSS) animations for iOS. An easy to use library of iOS animations. As easy to use as an easy thing.

wobbly See Wobbly in action (examples) Add a drop of honey ?? to your project wobbly has a bunch of cool, fun, and easy to use iOS animations for you

Sagaya Abdulhafeez 150 Dec 23, 2021
(Animate CSS) animations for iOS. An easy to use library of iOS animations. As easy to use as an easy thing.

wobbly See Wobbly in action (examples) Add a drop of honey ?? to your project wobbly has a bunch of cool, fun, and easy to use iOS animations for you

Sagaya Abdulhafeez 150 Dec 23, 2021
Awesome IOS Styling with SwiftUI, Animation, Effects, Gesture ⭐️

Awesome SwiftUI Styling with SwiftUI ⭐️ This repository is dedicated to IOS styling using SwiftUI. (often using Other Libraries.) I started collecting

SeungYeub Baek 1 Apr 5, 2022
You can dismiss modal by using gesture

RPModalGestureTransition You can dismiss modal by using gesture. Usage 1.Define animation You define animator class inherits UIViewControllerAnimatedT

Naoya Sugimoto 90 Apr 21, 2020
SwiftUI directed Server Driven UI

Server Driven UI (SDUI) Intentions Make a Server Driven UI module for SwiftUI applications that has a direct use. That way the application maintainer

Felipe Hilst 8 Nov 27, 2022
Pure SwiftUI state-driven library to present view sequences and hierarchies.

PathPresenter swiftUIOnboarding.mp4 Pure SwiftUI routing with transitions, animations, and .sheet() support. In SwiftUI, View is a function of the sta

Aleksandr Dremov 21 Nov 15, 2022
A library to simplify iOS animations in Swift.

Updated for Swift 4.2 Requires Xcode 10 and Swift 4.2. Installation Drop in the Spring folder to your Xcode project (make sure to enable "Copy items i

Meng To 14k Jan 3, 2023
Swift library for choreographing animations on the screen.

Spruce iOS Animation Library (and Android) What is it? Spruce is a lightweight animation library that helps choreograph the animations on the screen.

WillowTree, LLC 3.4k Jan 3, 2023
Composable animations in Swift

Composable animations in Swift. Blog Installation Cocoapods The easiest way to get started is to use CocoaPods. Just add the following line to your Po

Reid Chatham 195 Dec 5, 2022
Declarative chainable animations in Swift

Wave Declarative chainable animations in Swift ❤️ Support my apps ❤️ Push Hero - pure Swift native macOS application to test push notifications PasteP

Khoa 125 Oct 10, 2022
Easy to read and write chainable animations in Objective-C and Swift

Whats new in version 3.x? Swiftier syntax Swift 4 support Bug fixes and improvements Whats new in version 2.x? Re-architected from the ground up, no m

Jeff Hurray 3.2k Dec 30, 2022
SamuraiTransition is an open source Swift based library providing a collection of ViewController transitions featuring a number of neat “cutting” animations.

SamuraiTransiton is a ViewController transition framework in Swift. It is an animation as if Samurai cut out the screen with a sword. transition types

hachinobu 273 Dec 29, 2022
⛓ Easy to Read and Write Multi-chain Animations Lib in Objective-C and Swift.

中文介绍 This project is inspired by JHChainableAnimations! Why Choose LSAnimator & CoreAnimator? You can write complex and easy-to-maintain animations in

木子 1.6k Nov 22, 2022
This repo contains swift collection of gui, games, menu, animations, music, payment, etc... for iOS, macOS, watchOS and tvOS

Swift-Collections About: This repo contains a collection of projects built using swift and objective-c Contains projects for macOS iOS iPad watchOS tv

Krisna Pranav 6 Nov 15, 2022