SlideShare una empresa de Scribd logo
1 de 48
Animation in iOS
   Alexis Goldstein
   @alexisgoldstein
Agenda for Today
• Animation Sample Code
• UIView Animations:
 •   Animatable Properties
 •   Animation Options
 •   Transitions
• CoreAnimation:
 •   Implicit Animations
 •   Explicit Animations
• Where to go to learn more
Sample Code
• I’ve created some basic sample code to go
  along with this talk.
  • I leveraged Nathan Eror’s CA360 project
     as a base, and then added all new
     examples for this talk.
• You can find my sample code at: http://
  github.com/alexisgo/AnimationTalk
• You can find these slides at: http://bit.ly/
  alexisAnim
About Me
•   Spent seven years in technology on Wall Street.

•   Quit to pursue my dreams of going indie.

•   Launched aut faciam, an iOS software house, in
    July 2010.

•   Director of Operations for Girl Develop IT:

    •   Aim is to provide low-cost, non-intimidating
        programming classes for women.
About You
•   How long have you been
    working with iOS?
•   What do you want to
    animate / what kinds of
    things have you used
    animation for?
UIView Animations
UIView Animations
• Powered by CoreAnimation.
• Hardware Accelerated:
 • Animations happen on the GPU,
   rather than the CPU, to improve
   performance.
UIView Animations
•   How you perform a UIView animation depends on
    the iOS version.

•   iOS 4.0 and later:

    •   block-based animation methods, such as
        animateWithDuration: animations:
        completion:
    •   iOS 3.2 and earlier:

        •   beginAnimation and
            commitAnimations
Blocks (in 30 seconds)
•   Blocks are objects that encapsulate a section of
    code that can be executed at any time.
•   ^ introduces a block.
•   When used as method or function arguments,
    blocks are a type of callback.
    •  “When invoked, the method or function performs some work and, at
       the appropriate moments, calls back to the invoking code—via the block
       —to request additional information or to obtain application-specific
       behavior from it.” -- A Short Practical Guide to Blocks
•   Blocks have access to the local variables, parameters & even
    stack variables of the method you define it in.
•   Blocks also have access to functions and global variables,
    including instance variables.
UIView Animations: what we’ll focus
on today
 •   How you perform a UIView animation depends on
     the OS version.

     •   iOS 4.0 and later:

         •   block-based animation methods, such as
             animateWithDuration: animations:
             completion:

     •   iOS 3.2 and earlier:

         •   beginAnimation and
             commitAnimations
UIView Animations
• There are certain properties in
  UIView that are animatable.
• You create UIView animations by
  changing the value of these animatable
  properties from within an animation
  block (iOS 4.0+)
          animations:^ { ... }
UIView Animatable Properties
Property                 Description
  frame    The view’s frame rectangle
 bounds    The view’s bounding rectangle
 center    The center of the frame
          The transform applied to the view,
transform
          relative to the center of its bounds
  alpha    The view’s level of transparency
UIView’s animateWithDuration

• The most basic method to use to
  create UIView animations is
      animateWithDuration:
      animations:
Animating a change in Alpha
[UIView animateWithDuration:1.0
    animations:^

   {


      [myView setAlpha:1.0];

   }];

Demo: SetAlpha.m in the sample code
Animating a change in Center
[UIView animateWithDuration:1.0
    animations:^
 

 {
 

 
 [myView setCenter:
          CGPointMake(200, 200)];
 

 }];
Animating a Transform
    [UIView animateWithDuration:1.0
    animations:^


 {

 
 
 [myView setTransform:
          CGAffineTransformMakeRotatio
          n(M_PI)];

 
 }];
Nesting Animation Blocks
• You can nest animations inside one
  another
• See NestedAnimations.m in the
  sample code
   • http://github.com/alexisgo/
     AnimationTalk
UIView Animation Options
•   You can also configure the animation through
    UIViewAnimationOptions.
•   In iOS 4.0+, these are set through the
    options: argument of
    animateWithDuration: delay:
    options: animations: completion:
     •   In iOS 3.2 and earlier: Setter methods in
         several class methods of UIView.
Animation Options
 [UIView animateWithDuration: 2
       delay: 1.2
       options: (UIViewAnimationOptions)options
       animations:^{ ... }
       completion:^(BOOL finished) { ... } ];
Animation Options
•   UIViewAnimationOptionAllowUserInteraction
    •   Allows user interaction during an animation (off by
        default).
• UIViewAnimationOptionAutoreverse
  • Runs the animation back and forth, in a loop
• UIViewAnimationOptionBeginFromCurrentState
  • To avoid jumps between animations, if a second
      animation starts midway through another
      animation.
•   For the full list of all options, search for
    UIViewAnimationOptions at http://bit.ly/cBMPMg
Transitions
• iOS 4.0+:
  •   transitionFromView:toView:duration:options:co
      mpletion:

  •   transitionWithView:duration:options:animations:
      completion

• iOS 3.2 and earlier:
  •   setAnimationTransition:forView:cache:
Transitions: CurlUp
To create a curling effect on a view:

 [UIView transitionWithView: myView

 
 
 
 
 duration:2.0 
options:UIViewAnimationOptionTransitionCurl
Up

 
 
 
 
 animations:^{ ... }

 
 
 
 
 completion:nil
     ];
Transitions: CurlUp
• Please BEWARE your Code Sense!
• Make sure you are using the correct option
 • DO NOT WANT
    UIViewAnimationTransitionCurlUp!
   •   This is the old enum used with the (pre-blocks)
       setAnimationTransition method.

• You want:
  UIViewAnimationOptionTransitionCurl
  Up
Transitions: CurlUp
• If you’d like to transition from an old view to a new
   view, and want the old view to be removed from the
   view hierarchy, and the new one added, use:
   
 [UIView transitionFromView:myView

 
 
 
 
 
 toView:newView

 
 
 
 
 duration:2.0
options:UIViewAnimationOptionTransitionCurlUp

 
 
 
 
 completion:nil];
Transitions: Flip
   [UIView transitionWithView:transitionView

 
 
 
 
 duration:2.0
options:UIViewAnimationOptionTransitionFlipFromLeft

 
 
 
 
 animations: nil

 
 
 
 
 completion:^(BOOL finished)

 
 
 
 
 {

 
 
 
 
 
 ...

 
 
 
 
 }];
UIView Resources
    Apple Docs:
•   Getting Started with Graphics and Animation

•   “Animating Views” section of the View Programming
    Guide for iOS
WWDC 2010 Talks & Sample Code:
•Building Animation Driven Interfaces

•   iPlant
CoreAnimation
UIView or CoreAnimation?
• Almost always, you should use UIView
  animations.
When should you use Core Animation?

 •   Use CoreAnimation when you can’t accomplish
     what you need with UIView animations:
     •   You want to specify motion along a path
         •   UIView gives you linear paths

         •   CoreAnimation lets you specify any path

     •   You want to animate properties that are not
         animatable in UIView, such as: zPosition,
         cornerRadius, borderWidth, or borderColor.
     •   You have something very lightweight or short-
         lived.
When should you use Core Animation?

 •   A great example of a good time to use Core
     Animation is if want to rotate a UIView.
     • With UIView animations, we can only rotate
       around the default anchorPoint of the
       UIView, which is the middle of the view.
     • But you can modify that default anchor point
       through the CALayer of that viewew:
         [myView.layer.anchorPoint =
         CGPointMake(0,0);
 •   DEMO: Great visualization of this is in LayerTransforms.m class in Nathan
     Eror’s CA360 project (http://github.com/neror/CA360)
About Core Animation
• What is it? A compositing and animation
  API.
• Uses CALayer:
 • Layers have hierarchies, just like UIViews.
 • Can add, remove and reorder CALayers
      in the same way you add/remove/reorder
      UIViews.
•   Hardware Accelerated.
•   Interpolation of animations happens away
    from the main thread.
Jargon Alert! Compositing
COMPOSITING:
“The combining of visual elements from separate
sources into single images, often to create the illusion
that all those elements are parts of the same scene.”
       --http://en.wikipedia.org/wiki/Compositing



INTERPOLATION:
Deriving the value of one or more
unknown intermediate points
based known start and end points.
  Image source:
  http://en.wikipedia.org/wiki/
  Linear_interpolation
Using Core Animation

 Remember to
 #import <QuartzCore/QuartzCore.h>
 and to add the QuartzCore framework
 to your project.
First Step! Adding Content to your
Layer
  There are three ways to add content to a
  CALayer:
   1. Set the contents property on the layer
      using a CGImageRef
  2. Use a delegate to provide or draw the content
  3. Subclass CALayer and override one of the
     display methods
Adding Layer Content

• Excellent details on the different ways
  to do this can be found at:
   • http://developer.apple.com/library/
     ios/documentation/Cocoa/
     Conceptual/CoreAnimation_guide/
     Articles/
     ProvidingCALayerContent.html
Types of Animation: Implicit vs Explicit

 •   CoreAnimation has both implicit and explicit
     animations.
 •   Implicit Animations:
     • Implicit animations occur automatically
       whenever you modify an animatable layer
       property. (Sweet!)
 •   Explicit Animations:
     •   Explicit animations are created and then explicitly
         added to your layer by calling addAnimation:
Implicit Animation
•   When you set layer properties, the next time the
    run-loop gets control, it implements a transaction.
    • That transaction will cause all the layer
      properties that have changed to animate
      according to certain defaults.
    •   To override these defaults, you can use
        CATransaction.
• Sample code: BasicAnimation.m
Overriding Implicit Animation Defaults

 •   Let’s say we have the following implicit animation:
             myLayer.position = CGMakePoint(100,
             200);
 •   If we want this to take a bit longer, we can add:
         [CATransaction setAnimationDuration: 5];
         [CATransaction
            setAnimationTimingFunction: [CAMediaTimingFunction
            functionWithName:kCAMediaTimingFunctionEaseInEaseOut]
         myLayer.position = CGMakePoint(200,100);
Adding Drop Shadows
•   @property CGPathRef shadowPath
•   You specify where the layer is opaque
•   The compositor takes care of creating the drop
    shadow, and it does so by caching a shadow bitmap.
        COMPOSITING:
        The combining of visual elements from separate sources
        into single images, often to create the illusion that all
        those elements are parts of the same scene.
           Source: http://en.wikipedia.org/wiki/Compositing

•   Sample code: ShadowPath.m
Explicit Animations
• If you want more control over your
  animations, use Explicit Animations:
 • CABasicAnimation
 • CAKeyframeAnimation
 • CAAnimationGroup
 • CATransition
How to Create Explicit Animations
 •   Use keyPath to specify which property you are
     changing.
     •   @”position.x”
     •   @”transform.scale”
 •   Specify a from value and a to value (make something
     change).
 •   Add the animation to the layer.
           [CABasicAnimation *basic =
           [CABasicAnimation
               animationWithKeyPath:@”opacity”];
           ...
           [myView.layer addAnimation:basic];
CABasicAnimation
• Provides simple interpolation for a layer
  property.
• Simple example: BasicAnimation.m
Explicit Animations
• Please note: The model value DOES
  NOT CHANGE! The animation is
  changing the presentation only.
Explicit Animations: Making it Stick
• Because you are not changing the
    underlying model, the layer will go back to
    where it was before the animation--unless
    you also change the model.
•   Let’s examine BasicAnimation.m from the
    sample code.
•   For more on this topic:
        • http://bit.ly/bKxQPJ
        • WWDC10’s “Core Animation in
Keyframe Animations
• You provide a set of key frames, and Core
  Animation fills in the gaps.
• You can provide the frames through either:
 •   An array of values

 •   Series of points in a CGPathRef
Cubic Keyframe Animations
•   Interpolation is usually linear -- so
    interpolating between two points will get you
    a straight line.

•   Starting in iOS 4.0, a new calculationMode
    was added, which calculates the interpolation
    based on the two points AS WELL AS the
    points surrounding is--giving a cubic
    interpolation.

•   animation.calculationMode =
    kCAAnimationCubic

•   Sample code: Keyframe.m
CA360 Project
•   Nathan Eror (@neror) has an excellent resource
    on GitHub, CA360, which I used as a base for my
    sample code

•   I highly recommend checking it out

    •   http://github.com/neror/CA360
Resources to Learn More
 •  Apple Docs
 •  Getting Started with Graphics and Animation
 •  Core Animation Programming Guide
 •  “Animating Views” section of the View Programming
    Guide for iOS
WWDC 2010 Talks:
 •  Building Animation Driven Interfaces
 •  Core Animation in Practice: Part 1
 •  Core Animation in Practice: Part II
Nathan Eror, Freetime Studios
 •  Talk from 360 iDev 2009
 •  360 sample code: http://github.com/neror/CA360
 •  FTUtils: http://ftutils.com/

Más contenido relacionado

La actualidad más candente

[Android] Android Animation
[Android] Android Animation[Android] Android Animation
[Android] Android AnimationNikmesoft Ltd
 
Getting Started with CoreGraphics
Getting Started with CoreGraphicsGetting Started with CoreGraphics
Getting Started with CoreGraphicsXamarin
 
Xamarin 9/10 San Diego Meetup
Xamarin 9/10 San Diego MeetupXamarin 9/10 San Diego Meetup
Xamarin 9/10 San Diego MeetupSeamgen
 
Android Training (Animation)
Android Training (Animation)Android Training (Animation)
Android Training (Animation)Khaled Anaqwa
 
Beginners Guide to Modeling with Maya
Beginners Guide to Modeling with MayaBeginners Guide to Modeling with Maya
Beginners Guide to Modeling with MayaPaddy Lock
 
Android animations
Android animationsAndroid animations
Android animationsKumar
 
FMX2013: Butterfly Effect
FMX2013: Butterfly EffectFMX2013: Butterfly Effect
FMX2013: Butterfly EffectRenaldas Zioma
 
Crafting interactions with Core Animations, David Ortinau
Crafting interactions with Core Animations, David OrtinauCrafting interactions with Core Animations, David Ortinau
Crafting interactions with Core Animations, David OrtinauXamarin
 
Animations in iOS with Facebook POP
Animations in iOS with Facebook POPAnimations in iOS with Facebook POP
Animations in iOS with Facebook POPEduard Panasiuk
 
Introduction to POP animation engine
Introduction to POP animation engineIntroduction to POP animation engine
Introduction to POP animation engineSubhransu Behera
 
Design your 3d game engine
Design your 3d game engineDesign your 3d game engine
Design your 3d game engineDaosheng Mu
 
Game Engine Architecture
Game Engine ArchitectureGame Engine Architecture
Game Engine ArchitectureAttila Jenei
 
【Unite 2017 Tokyo】Anima2Dについて語るで!2Dアニメーションの未来
【Unite 2017 Tokyo】Anima2Dについて語るで!2Dアニメーションの未来【Unite 2017 Tokyo】Anima2Dについて語るで!2Dアニメーションの未来
【Unite 2017 Tokyo】Anima2Dについて語るで!2Dアニメーションの未来Unite2017Tokyo
 
Animate The Web With Ember.js - Jessica Jordan
Animate The Web With Ember.js - Jessica JordanAnimate The Web With Ember.js - Jessica Jordan
Animate The Web With Ember.js - Jessica JordanJessica Jordan
 
ميهين
ميهينميهين
ميهينAhmed
 
Academy PRO: React native - building first scenes
Academy PRO: React native - building first scenesAcademy PRO: React native - building first scenes
Academy PRO: React native - building first scenesBinary Studio
 

La actualidad más candente (20)

[Android] Android Animation
[Android] Android Animation[Android] Android Animation
[Android] Android Animation
 
Android animation theory
Android animation theoryAndroid animation theory
Android animation theory
 
Getting Started with CoreGraphics
Getting Started with CoreGraphicsGetting Started with CoreGraphics
Getting Started with CoreGraphics
 
Xamarin 9/10 San Diego Meetup
Xamarin 9/10 San Diego MeetupXamarin 9/10 San Diego Meetup
Xamarin 9/10 San Diego Meetup
 
Android Training (Animation)
Android Training (Animation)Android Training (Animation)
Android Training (Animation)
 
Android - Graphics Animation in Android
Android - Graphics Animation in AndroidAndroid - Graphics Animation in Android
Android - Graphics Animation in Android
 
Beginners Guide to Modeling with Maya
Beginners Guide to Modeling with MayaBeginners Guide to Modeling with Maya
Beginners Guide to Modeling with Maya
 
Intro to auto_desk_maya2015
Intro to auto_desk_maya2015Intro to auto_desk_maya2015
Intro to auto_desk_maya2015
 
Android animations
Android animationsAndroid animations
Android animations
 
FMX2013: Butterfly Effect
FMX2013: Butterfly EffectFMX2013: Butterfly Effect
FMX2013: Butterfly Effect
 
Crafting interactions with Core Animations, David Ortinau
Crafting interactions with Core Animations, David OrtinauCrafting interactions with Core Animations, David Ortinau
Crafting interactions with Core Animations, David Ortinau
 
Animations in iOS with Facebook POP
Animations in iOS with Facebook POPAnimations in iOS with Facebook POP
Animations in iOS with Facebook POP
 
Introduction to POP animation engine
Introduction to POP animation engineIntroduction to POP animation engine
Introduction to POP animation engine
 
Design your 3d game engine
Design your 3d game engineDesign your 3d game engine
Design your 3d game engine
 
Game Engine Architecture
Game Engine ArchitectureGame Engine Architecture
Game Engine Architecture
 
【Unite 2017 Tokyo】Anima2Dについて語るで!2Dアニメーションの未来
【Unite 2017 Tokyo】Anima2Dについて語るで!2Dアニメーションの未来【Unite 2017 Tokyo】Anima2Dについて語るで!2Dアニメーションの未来
【Unite 2017 Tokyo】Anima2Dについて語るで!2Dアニメーションの未来
 
Animate The Web With Ember.js - Jessica Jordan
Animate The Web With Ember.js - Jessica JordanAnimate The Web With Ember.js - Jessica Jordan
Animate The Web With Ember.js - Jessica Jordan
 
ميهين
ميهينميهين
ميهين
 
Showreel
ShowreelShowreel
Showreel
 
Academy PRO: React native - building first scenes
Academy PRO: React native - building first scenesAcademy PRO: React native - building first scenes
Academy PRO: React native - building first scenes
 

Destacado

CS193P Lecture 5 View Animation
CS193P Lecture 5 View AnimationCS193P Lecture 5 View Animation
CS193P Lecture 5 View Animationonoaonoa
 
Realtime system with pushpin fanout, controlling your devices
Realtime system with pushpin fanout, controlling your devicesRealtime system with pushpin fanout, controlling your devices
Realtime system with pushpin fanout, controlling your devicesLe Kien Truc
 
06 View Controllers
06 View Controllers06 View Controllers
06 View ControllersMahmoud
 
01 Introduction
01 Introduction01 Introduction
01 IntroductionMahmoud
 
03 Custom Classes
03 Custom Classes03 Custom Classes
03 Custom ClassesMahmoud
 
04 Model View Controller
04 Model View Controller04 Model View Controller
04 Model View ControllerMahmoud
 
02 Objective C
02 Objective C02 Objective C
02 Objective CMahmoud
 
NGHIÊN CỨU XÂY DỰNG ỨNG DỤNG CHO HỆ ĐIỀU HÀNH iOS
NGHIÊN CỨU XÂY DỰNG ỨNG DỤNG CHO HỆ ĐIỀU HÀNH iOSNGHIÊN CỨU XÂY DỰNG ỨNG DỤNG CHO HỆ ĐIỀU HÀNH iOS
NGHIÊN CỨU XÂY DỰNG ỨNG DỤNG CHO HỆ ĐIỀU HÀNH iOSVàng Cao Thanh
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core AnimationJohn Wilker
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View ControllersBob McCune
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBob McCune
 
Mastering Media with AV Foundation
Mastering Media with AV FoundationMastering Media with AV Foundation
Mastering Media with AV FoundationChris Adamson
 
Master Video with AV Foundation
Master Video with AV FoundationMaster Video with AV Foundation
Master Video with AV FoundationBob McCune
 
Composing and Editing Media with AV Foundation
Composing and Editing Media with AV FoundationComposing and Editing Media with AV Foundation
Composing and Editing Media with AV FoundationBob McCune
 
20 iOS developer interview questions
20 iOS developer interview questions20 iOS developer interview questions
20 iOS developer interview questionsArc & Codementor
 
iOS Developer Interview Questions
iOS Developer Interview QuestionsiOS Developer Interview Questions
iOS Developer Interview QuestionsClark Davidson
 

Destacado (20)

05 Views
05 Views05 Views
05 Views
 
CS193P Lecture 5 View Animation
CS193P Lecture 5 View AnimationCS193P Lecture 5 View Animation
CS193P Lecture 5 View Animation
 
Realtime system with pushpin fanout, controlling your devices
Realtime system with pushpin fanout, controlling your devicesRealtime system with pushpin fanout, controlling your devices
Realtime system with pushpin fanout, controlling your devices
 
09 Data
09 Data09 Data
09 Data
 
06 View Controllers
06 View Controllers06 View Controllers
06 View Controllers
 
01 Introduction
01 Introduction01 Introduction
01 Introduction
 
03 Custom Classes
03 Custom Classes03 Custom Classes
03 Custom Classes
 
iOS: View Controllers
iOS: View ControllersiOS: View Controllers
iOS: View Controllers
 
04 Model View Controller
04 Model View Controller04 Model View Controller
04 Model View Controller
 
02 Objective C
02 Objective C02 Objective C
02 Objective C
 
NGHIÊN CỨU XÂY DỰNG ỨNG DỤNG CHO HỆ ĐIỀU HÀNH iOS
NGHIÊN CỨU XÂY DỰNG ỨNG DỤNG CHO HỆ ĐIỀU HÀNH iOSNGHIÊN CỨU XÂY DỰNG ỨNG DỤNG CHO HỆ ĐIỀU HÀNH iOS
NGHIÊN CỨU XÂY DỰNG ỨNG DỤNG CHO HỆ ĐIỀU HÀNH iOS
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View Controllers
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngine
 
Mastering Media with AV Foundation
Mastering Media with AV FoundationMastering Media with AV Foundation
Mastering Media with AV Foundation
 
Master Video with AV Foundation
Master Video with AV FoundationMaster Video with AV Foundation
Master Video with AV Foundation
 
Composing and Editing Media with AV Foundation
Composing and Editing Media with AV FoundationComposing and Editing Media with AV Foundation
Composing and Editing Media with AV Foundation
 
20 iOS developer interview questions
20 iOS developer interview questions20 iOS developer interview questions
20 iOS developer interview questions
 
iOS Developer Interview Questions
iOS Developer Interview QuestionsiOS Developer Interview Questions
iOS Developer Interview Questions
 
Graphics Libraries
Graphics LibrariesGraphics Libraries
Graphics Libraries
 

Similar a Animation in iOS

Сергій Міськів, «SwiftUI: Animations»
Сергій Міськів, «SwiftUI: Animations»Сергій Міськів, «SwiftUI: Animations»
Сергій Міськів, «SwiftUI: Animations»Sigma Software
 
iOS Development: What's New
iOS Development: What's NewiOS Development: What's New
iOS Development: What's NewNascentDigital
 
Demystifying Angular Animations
Demystifying Angular AnimationsDemystifying Angular Animations
Demystifying Angular AnimationsGil Fink
 
Advanced UI styling and animations for iOS
Advanced UI styling and animations for iOSAdvanced UI styling and animations for iOS
Advanced UI styling and animations for iOSMike Gerasymenko
 
Session 15 - Working with Image, Scroll, Collection, Picker, and Web View
Session 15  - Working with Image, Scroll, Collection, Picker, and Web ViewSession 15  - Working with Image, Scroll, Collection, Picker, and Web View
Session 15 - Working with Image, Scroll, Collection, Picker, and Web ViewVu Tran Lam
 
Building your first iOS app using Xamarin
Building your first iOS app using XamarinBuilding your first iOS app using Xamarin
Building your first iOS app using XamarinGill Cleeren
 
Motion design in FIori
Motion design in FIoriMotion design in FIori
Motion design in FIoriRoman Rommel
 
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextHi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextMugunth Kumar
 
Programming iOS in C#
Programming iOS in C#Programming iOS in C#
Programming iOS in C#Frank Krueger
 
Android webinar class_4
Android webinar class_4Android webinar class_4
Android webinar class_4Edureka!
 
Building GPU-Accelerated Mobile Application Interfaces with Starling and Feat...
Building GPU-Accelerated Mobile Application Interfaces with Starling and Feat...Building GPU-Accelerated Mobile Application Interfaces with Starling and Feat...
Building GPU-Accelerated Mobile Application Interfaces with Starling and Feat...Joseph Labrecque
 
UI Animations in Meteor
UI Animations in MeteorUI Animations in Meteor
UI Animations in MeteorNick Wientge
 
Practical animation
Practical animationPractical animation
Practical animationSV.CO
 
CoreML New Features in 2020
CoreML New Features in 2020CoreML New Features in 2020
CoreML New Features in 2020Abby Lai
 
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)Chris Adamson
 
Shift Remote: JS - PoseDance: Build a TikTok Trainer - Jennifer Looper (Micro...
Shift Remote: JS - PoseDance: Build a TikTok Trainer - Jennifer Looper (Micro...Shift Remote: JS - PoseDance: Build a TikTok Trainer - Jennifer Looper (Micro...
Shift Remote: JS - PoseDance: Build a TikTok Trainer - Jennifer Looper (Micro...Shift Conference
 
Seven Peaks Speaks - Android Jetpack Compose Animation
Seven Peaks Speaks - Android Jetpack Compose AnimationSeven Peaks Speaks - Android Jetpack Compose Animation
Seven Peaks Speaks - Android Jetpack Compose AnimationSeven Peaks Speaks
 
Swift LA Meetup at eHarmony- Swift and Enterprise and eHarmony with Heena Ras...
Swift LA Meetup at eHarmony- Swift and Enterprise and eHarmony with Heena Ras...Swift LA Meetup at eHarmony- Swift and Enterprise and eHarmony with Heena Ras...
Swift LA Meetup at eHarmony- Swift and Enterprise and eHarmony with Heena Ras...Claire Townend Gee
 

Similar a Animation in iOS (20)

Сергій Міськів, «SwiftUI: Animations»
Сергій Міськів, «SwiftUI: Animations»Сергій Міськів, «SwiftUI: Animations»
Сергій Міськів, «SwiftUI: Animations»
 
iOS Development: What's New
iOS Development: What's NewiOS Development: What's New
iOS Development: What's New
 
Demystifying Angular Animations
Demystifying Angular AnimationsDemystifying Angular Animations
Demystifying Angular Animations
 
Advanced UI styling and animations for iOS
Advanced UI styling and animations for iOSAdvanced UI styling and animations for iOS
Advanced UI styling and animations for iOS
 
Session 15 - Working with Image, Scroll, Collection, Picker, and Web View
Session 15  - Working with Image, Scroll, Collection, Picker, and Web ViewSession 15  - Working with Image, Scroll, Collection, Picker, and Web View
Session 15 - Working with Image, Scroll, Collection, Picker, and Web View
 
Building your first iOS app using Xamarin
Building your first iOS app using XamarinBuilding your first iOS app using Xamarin
Building your first iOS app using Xamarin
 
Motion design in FIori
Motion design in FIoriMotion design in FIori
Motion design in FIori
 
iOS Core Animation
iOS Core AnimationiOS Core Animation
iOS Core Animation
 
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextHi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreText
 
Programming iOS in C#
Programming iOS in C#Programming iOS in C#
Programming iOS in C#
 
Android webinar class_4
Android webinar class_4Android webinar class_4
Android webinar class_4
 
Building GPU-Accelerated Mobile Application Interfaces with Starling and Feat...
Building GPU-Accelerated Mobile Application Interfaces with Starling and Feat...Building GPU-Accelerated Mobile Application Interfaces with Starling and Feat...
Building GPU-Accelerated Mobile Application Interfaces with Starling and Feat...
 
UI Animations in Meteor
UI Animations in MeteorUI Animations in Meteor
UI Animations in Meteor
 
Practical animation
Practical animationPractical animation
Practical animation
 
CoreML New Features in 2020
CoreML New Features in 2020CoreML New Features in 2020
CoreML New Features in 2020
 
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
 
Introduction of Xcode
Introduction of XcodeIntroduction of Xcode
Introduction of Xcode
 
Shift Remote: JS - PoseDance: Build a TikTok Trainer - Jennifer Looper (Micro...
Shift Remote: JS - PoseDance: Build a TikTok Trainer - Jennifer Looper (Micro...Shift Remote: JS - PoseDance: Build a TikTok Trainer - Jennifer Looper (Micro...
Shift Remote: JS - PoseDance: Build a TikTok Trainer - Jennifer Looper (Micro...
 
Seven Peaks Speaks - Android Jetpack Compose Animation
Seven Peaks Speaks - Android Jetpack Compose AnimationSeven Peaks Speaks - Android Jetpack Compose Animation
Seven Peaks Speaks - Android Jetpack Compose Animation
 
Swift LA Meetup at eHarmony- Swift and Enterprise and eHarmony with Heena Ras...
Swift LA Meetup at eHarmony- Swift and Enterprise and eHarmony with Heena Ras...Swift LA Meetup at eHarmony- Swift and Enterprise and eHarmony with Heena Ras...
Swift LA Meetup at eHarmony- Swift and Enterprise and eHarmony with Heena Ras...
 

Animation in iOS

  • 1. Animation in iOS Alexis Goldstein @alexisgoldstein
  • 2. Agenda for Today • Animation Sample Code • UIView Animations: • Animatable Properties • Animation Options • Transitions • CoreAnimation: • Implicit Animations • Explicit Animations • Where to go to learn more
  • 3. Sample Code • I’ve created some basic sample code to go along with this talk. • I leveraged Nathan Eror’s CA360 project as a base, and then added all new examples for this talk. • You can find my sample code at: http:// github.com/alexisgo/AnimationTalk • You can find these slides at: http://bit.ly/ alexisAnim
  • 4. About Me • Spent seven years in technology on Wall Street. • Quit to pursue my dreams of going indie. • Launched aut faciam, an iOS software house, in July 2010. • Director of Operations for Girl Develop IT: • Aim is to provide low-cost, non-intimidating programming classes for women.
  • 5. About You • How long have you been working with iOS? • What do you want to animate / what kinds of things have you used animation for?
  • 7. UIView Animations • Powered by CoreAnimation. • Hardware Accelerated: • Animations happen on the GPU, rather than the CPU, to improve performance.
  • 8. UIView Animations • How you perform a UIView animation depends on the iOS version. • iOS 4.0 and later: • block-based animation methods, such as animateWithDuration: animations: completion: • iOS 3.2 and earlier: • beginAnimation and commitAnimations
  • 9. Blocks (in 30 seconds) • Blocks are objects that encapsulate a section of code that can be executed at any time. • ^ introduces a block. • When used as method or function arguments, blocks are a type of callback. • “When invoked, the method or function performs some work and, at the appropriate moments, calls back to the invoking code—via the block —to request additional information or to obtain application-specific behavior from it.” -- A Short Practical Guide to Blocks • Blocks have access to the local variables, parameters & even stack variables of the method you define it in. • Blocks also have access to functions and global variables, including instance variables.
  • 10. UIView Animations: what we’ll focus on today • How you perform a UIView animation depends on the OS version. • iOS 4.0 and later: • block-based animation methods, such as animateWithDuration: animations: completion: • iOS 3.2 and earlier: • beginAnimation and commitAnimations
  • 11. UIView Animations • There are certain properties in UIView that are animatable. • You create UIView animations by changing the value of these animatable properties from within an animation block (iOS 4.0+) animations:^ { ... }
  • 12. UIView Animatable Properties Property Description frame The view’s frame rectangle bounds The view’s bounding rectangle center The center of the frame The transform applied to the view, transform relative to the center of its bounds alpha The view’s level of transparency
  • 13. UIView’s animateWithDuration • The most basic method to use to create UIView animations is animateWithDuration: animations:
  • 14. Animating a change in Alpha [UIView animateWithDuration:1.0 animations:^ { [myView setAlpha:1.0]; }]; Demo: SetAlpha.m in the sample code
  • 15. Animating a change in Center [UIView animateWithDuration:1.0 animations:^ { [myView setCenter: CGPointMake(200, 200)]; }];
  • 16. Animating a Transform [UIView animateWithDuration:1.0 animations:^ { [myView setTransform: CGAffineTransformMakeRotatio n(M_PI)]; }];
  • 17. Nesting Animation Blocks • You can nest animations inside one another • See NestedAnimations.m in the sample code • http://github.com/alexisgo/ AnimationTalk
  • 18. UIView Animation Options • You can also configure the animation through UIViewAnimationOptions. • In iOS 4.0+, these are set through the options: argument of animateWithDuration: delay: options: animations: completion: • In iOS 3.2 and earlier: Setter methods in several class methods of UIView.
  • 19. Animation Options [UIView animateWithDuration: 2 delay: 1.2 options: (UIViewAnimationOptions)options animations:^{ ... } completion:^(BOOL finished) { ... } ];
  • 20. Animation Options • UIViewAnimationOptionAllowUserInteraction • Allows user interaction during an animation (off by default). • UIViewAnimationOptionAutoreverse • Runs the animation back and forth, in a loop • UIViewAnimationOptionBeginFromCurrentState • To avoid jumps between animations, if a second animation starts midway through another animation. • For the full list of all options, search for UIViewAnimationOptions at http://bit.ly/cBMPMg
  • 21. Transitions • iOS 4.0+: • transitionFromView:toView:duration:options:co mpletion: • transitionWithView:duration:options:animations: completion • iOS 3.2 and earlier: • setAnimationTransition:forView:cache:
  • 22. Transitions: CurlUp To create a curling effect on a view: [UIView transitionWithView: myView duration:2.0 options:UIViewAnimationOptionTransitionCurl Up animations:^{ ... } completion:nil ];
  • 23. Transitions: CurlUp • Please BEWARE your Code Sense! • Make sure you are using the correct option • DO NOT WANT UIViewAnimationTransitionCurlUp! • This is the old enum used with the (pre-blocks) setAnimationTransition method. • You want: UIViewAnimationOptionTransitionCurl Up
  • 24. Transitions: CurlUp • If you’d like to transition from an old view to a new view, and want the old view to be removed from the view hierarchy, and the new one added, use: [UIView transitionFromView:myView toView:newView duration:2.0 options:UIViewAnimationOptionTransitionCurlUp completion:nil];
  • 25. Transitions: Flip [UIView transitionWithView:transitionView duration:2.0 options:UIViewAnimationOptionTransitionFlipFromLeft animations: nil completion:^(BOOL finished) { ... }];
  • 26. UIView Resources Apple Docs: • Getting Started with Graphics and Animation • “Animating Views” section of the View Programming Guide for iOS WWDC 2010 Talks & Sample Code: •Building Animation Driven Interfaces • iPlant
  • 28. UIView or CoreAnimation? • Almost always, you should use UIView animations.
  • 29. When should you use Core Animation? • Use CoreAnimation when you can’t accomplish what you need with UIView animations: • You want to specify motion along a path • UIView gives you linear paths • CoreAnimation lets you specify any path • You want to animate properties that are not animatable in UIView, such as: zPosition, cornerRadius, borderWidth, or borderColor. • You have something very lightweight or short- lived.
  • 30. When should you use Core Animation? • A great example of a good time to use Core Animation is if want to rotate a UIView. • With UIView animations, we can only rotate around the default anchorPoint of the UIView, which is the middle of the view. • But you can modify that default anchor point through the CALayer of that viewew: [myView.layer.anchorPoint = CGPointMake(0,0); • DEMO: Great visualization of this is in LayerTransforms.m class in Nathan Eror’s CA360 project (http://github.com/neror/CA360)
  • 31. About Core Animation • What is it? A compositing and animation API. • Uses CALayer: • Layers have hierarchies, just like UIViews. • Can add, remove and reorder CALayers in the same way you add/remove/reorder UIViews. • Hardware Accelerated. • Interpolation of animations happens away from the main thread.
  • 32. Jargon Alert! Compositing COMPOSITING: “The combining of visual elements from separate sources into single images, often to create the illusion that all those elements are parts of the same scene.” --http://en.wikipedia.org/wiki/Compositing INTERPOLATION: Deriving the value of one or more unknown intermediate points based known start and end points. Image source: http://en.wikipedia.org/wiki/ Linear_interpolation
  • 33. Using Core Animation Remember to #import <QuartzCore/QuartzCore.h> and to add the QuartzCore framework to your project.
  • 34. First Step! Adding Content to your Layer There are three ways to add content to a CALayer: 1. Set the contents property on the layer using a CGImageRef 2. Use a delegate to provide or draw the content 3. Subclass CALayer and override one of the display methods
  • 35. Adding Layer Content • Excellent details on the different ways to do this can be found at: • http://developer.apple.com/library/ ios/documentation/Cocoa/ Conceptual/CoreAnimation_guide/ Articles/ ProvidingCALayerContent.html
  • 36. Types of Animation: Implicit vs Explicit • CoreAnimation has both implicit and explicit animations. • Implicit Animations: • Implicit animations occur automatically whenever you modify an animatable layer property. (Sweet!) • Explicit Animations: • Explicit animations are created and then explicitly added to your layer by calling addAnimation:
  • 37. Implicit Animation • When you set layer properties, the next time the run-loop gets control, it implements a transaction. • That transaction will cause all the layer properties that have changed to animate according to certain defaults. • To override these defaults, you can use CATransaction. • Sample code: BasicAnimation.m
  • 38. Overriding Implicit Animation Defaults • Let’s say we have the following implicit animation: myLayer.position = CGMakePoint(100, 200); • If we want this to take a bit longer, we can add: [CATransaction setAnimationDuration: 5]; [CATransaction setAnimationTimingFunction: [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut] myLayer.position = CGMakePoint(200,100);
  • 39. Adding Drop Shadows • @property CGPathRef shadowPath • You specify where the layer is opaque • The compositor takes care of creating the drop shadow, and it does so by caching a shadow bitmap. COMPOSITING: The combining of visual elements from separate sources into single images, often to create the illusion that all those elements are parts of the same scene. Source: http://en.wikipedia.org/wiki/Compositing • Sample code: ShadowPath.m
  • 40. Explicit Animations • If you want more control over your animations, use Explicit Animations: • CABasicAnimation • CAKeyframeAnimation • CAAnimationGroup • CATransition
  • 41. How to Create Explicit Animations • Use keyPath to specify which property you are changing. • @”position.x” • @”transform.scale” • Specify a from value and a to value (make something change). • Add the animation to the layer. [CABasicAnimation *basic = [CABasicAnimation animationWithKeyPath:@”opacity”]; ... [myView.layer addAnimation:basic];
  • 42. CABasicAnimation • Provides simple interpolation for a layer property. • Simple example: BasicAnimation.m
  • 43. Explicit Animations • Please note: The model value DOES NOT CHANGE! The animation is changing the presentation only.
  • 44. Explicit Animations: Making it Stick • Because you are not changing the underlying model, the layer will go back to where it was before the animation--unless you also change the model. • Let’s examine BasicAnimation.m from the sample code. • For more on this topic: • http://bit.ly/bKxQPJ • WWDC10’s “Core Animation in
  • 45. Keyframe Animations • You provide a set of key frames, and Core Animation fills in the gaps. • You can provide the frames through either: • An array of values • Series of points in a CGPathRef
  • 46. Cubic Keyframe Animations • Interpolation is usually linear -- so interpolating between two points will get you a straight line. • Starting in iOS 4.0, a new calculationMode was added, which calculates the interpolation based on the two points AS WELL AS the points surrounding is--giving a cubic interpolation. • animation.calculationMode = kCAAnimationCubic • Sample code: Keyframe.m
  • 47. CA360 Project • Nathan Eror (@neror) has an excellent resource on GitHub, CA360, which I used as a base for my sample code • I highly recommend checking it out • http://github.com/neror/CA360
  • 48. Resources to Learn More • Apple Docs • Getting Started with Graphics and Animation • Core Animation Programming Guide • “Animating Views” section of the View Programming Guide for iOS WWDC 2010 Talks: • Building Animation Driven Interfaces • Core Animation in Practice: Part 1 • Core Animation in Practice: Part II Nathan Eror, Freetime Studios • Talk from 360 iDev 2009 • 360 sample code: http://github.com/neror/CA360 • FTUtils: http://ftutils.com/

Notas del editor

  1. \n
  2. \n
  3. - Most of the topics I cover today have a dedicated file in the sample code demonstrating the techniques and methods I&apos;ll be talking about\n
  4. \n
  5. \n
  6. \n
  7. \n
  8. - Who is already using blocks in their code?\n- Who is not using blocks just yet, or isn&apos;t familiar with what blocks are?\n
  9. - Would any of you in the first group like to explain blocks in 30 seconds?\n
  10. \n
  11. - How many of you are using blocks now in your code?\n- Who would like to take a shot at explaining what blocks do?\n
  12. - How many of you are using blocks now in your code?\n- Who would like to take a shot at explaining what blocks do?\n
  13. - How many of you are using blocks now in your code?\n- Who would like to take a shot at explaining what blocks do?\n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. - I always\n
  32. - I always\n
  33. - I always forget to do this, and then waste time puzzling over compile errors \n
  34. - Since Core Animation is all about using CALayers, first we need to add some content to them!\n
  35. - I&apos;m not going to go through this, but it&apos;s covered thoroughly in the docs\n- For the rest of the talk, let&apos;s just assume your CALayers already have some content in them, and you want to animate those layers\n
  36. \n
  37. \n
  38. - this is a bit about how it works under the covers\n
  39. \n
  40. \n
  41. - how do you tell CA what property you are animating? you use a keyPath\n- you explicitly add the animation to the layer -- that&amp;#x2019;s how you kick off the animation\n
  42. \n
  43. - you have NOT changed your layer model\n- if you query the model during the animation, you&amp;#x2019;ll get the old value, not the presentation you&amp;#x2019;re seeing.\n
  44. - you have NOT changed your layer model\n- if you query the model during the animation, you&amp;#x2019;ll get the old value, not the presentation you&amp;#x2019;re seeing.\n
  45. \n
  46. \n
  47. \n
  48. \n