Stanford CS193p. Developing Applications for ios. Winter CS193p. Winter 2017

Similar documents
ios Mobile Development

What's New in UIKit Dynamics and Visual Effects Session 229

ITP 342 Mobile App Dev. Animation

Stanford CS193p. Developing Applications for ios. Spring CS193p. Spring 2016

Stanford CS193p. Developing Applications for ios. Spring CS193p. Spring 2016

Stanford CS193p. Developing Applications for ios. Winter CS193p. Winter 2017

ITP 342 Mobile App Dev. Animation

Assignment III: Graphing Calculator

Stanford CS193p. Developing Applications for ios. Winter CS193p. Winter 2017

SAMPLE CHAPTER. Brendan G. Lim Martin Conte Mac Donell MANNING

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015

Stanford CS193p. Developing Applications for ios. Spring Stanford CS193p. Spring 2012

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

Core Graphics and OpenGL ES. Dr. Sarah Abraham

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015

View Controller Lifecycle

ITP 342 Mobile App Dev. Animation

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

Assignment III: Graphing Calculator

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

Custom Drawing & Animation. CS 442: Mobile App Development Michael Saelee

CS193p Spring 2010 Thursday, April 29, 2010

Assignment III: Graphing Calculator

Modern User Interaction on ios

Custom Drawing & Animation. CS 442: Mobile App Development Michael Saelee

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

Stanford CS193p. Developing Applications for ios Fall Stanford CS193p. Fall 2013

Graphics and Animation

Lecture 5 Demo Code: FaceIt MVC and Gestures

Objective-C. Stanford CS193p Fall 2013

Mobile Application Programing: ios. Messaging

Using Flash Animation Basics

Assignment III: Graphing Calculator

Announcements. Today s Topics

Lecture 8 Demo Code: Cassini Multithreading

iphone Application Programming Lecture 3: Swift Part 2

Mobile Application Programming. Controls

Monday, 1 November The ios System

Announcements. Lab 2 is due next Monday (Sept 25 th ) by 11:59 PM. Late policy is 10% of lab total per day late. So -7.5 points per day late for lab 2

Praktikum Entwicklung von Mediensystemen mit

Advanced ios. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 20 11/01/2012

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

Cheng, CSE870. More Frameworks. Overview. Recap on OOP. Acknowledgements:

View Controller Advancements for ios8

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

Mobile Application Development

AUTO LAYOUT IS A UNICORN

Developing Applications for ios

What s New in imessage Apps

Intro. Scheme Basics. scm> 5 5. scm>

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

Mobile Development Lab 3

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Fall Stanford CS193p Fall 2010

What s New in tvos 12

Pong in Unity a basic Intro

Developing Applications for ios

: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics

Assignment II: Foundation Calculator

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

What s New in NSCollectionView Session 225

ios Mobile Development

Mastering Drag and Drop

ITP 342 Advanced Mobile App Dev. Memory

Automatic Duck Ximport AE User Guide

iphone Application Programming Lecture 3: Swift Part 2

Lecture 17 Priority Queues

Stanford CS193p. Developing Applications for ios. Winter CS193p. Winter 2017

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015

Introduction to HTML & CSS. Instructor: Beck Johnson Week 5

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

The first program: Little Crab

Type Checking in COOL (II) Lecture 10

CS193p Spring 2010 Monday, April 12, 2010

Designing iphone Applications

Media Playback and Recording. CS193W - Spring Lecture 3

Use Parametric notation. Interpret the effect that T has on the graph as motion.

OOP Design Conclusions and Variations

2D ANIMATION & INTERACTION COURSE WEEK 5 QUICK REFERENCE

Questions. Exams: no. Get by without own Mac? Why ios? ios vs Android restrictions. Selling in App store how hard to publish? Future of Objective-C?

the gamedesigninitiative at cornell university Lecture 12 2D Animation

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015

Event Delivery: The Responder Chain

The Best of Both Worlds: Using UIKit with OpenGL

Contents. Remote Control Playback Controls What s on TV? Using the OK Button Using the Info Button... 6

Swift API Design Guidelines

ios Mobile Development

hw6, BFS, debugging CSE 331 Section 5 10/25/12 Slides by Kellen Donohue

The Design and Implementation of a Lightweight Game Engine for the iphone Platform

4. Use of complex numbers in deriving a solution to an LTI ODE with sinusoidal signal, and getting from such an expression to amplitude and phase lag

COMP327 Mobile Computing Session:

1 Dynamic Memory continued: Memory Leaks

CS193p Spring 2010 Wednesday, March 31, 2010

Fall UI Design and Implementation 1

Smoother Graphics Taking Control of Painting the Screen

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

CoderDojo Activity Cards: The Cards (Animation2.html): How to use: Student comes to mentor, and together they choose a card to do next.

Chapter 1: Object-Oriented Programming Using C++

Mobile Application Programming. Layout Techniques

Transcription:

Stanford Developing Applications for ios

Today Timer Periodically execute a block of code Blinking FaceIt Demo Animation Animating changes to UIViews Smoother Blinking FaceIt Head-shaking FaceIt Animating using simulated physics (time permitting)

Timer Used to execute code periodically You can set it up to go off once at at some time in the future, or to repeatedly go off If repeatedly, the system will not guarantee exactly when it goes off, so this is not real-time But for most UI order of magnitude activities, it s perfectly fine We don t generally use it for animation (more on that later) It s more for larger-grained activities Run loops Timers work with run loops (which we have not and will not talk about) So for your purposes, you can only use Timer on the main queue Check out the documentation if you want to learn about run loops and timers on other queues

Timer Fire one off with this method class func scheduledtimer( withtimeinterval: TimeInterval, repeats: Bool, block: (Timer) -> Void ) -> Timer Example private weak var timer: Timer? timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { // your code here } Every 2 seconds (approximately), the closure will be executed. Note that the var we stored the timer in is weak. That s okay because the run loop will keep a strong pointer to this as long as it s scheduled.

NSTimer Stopping a repeating timer We need to be a bit careful with repeating timers you don t want them running forever. You stop them by calling invalidate() on them timer.invalidate() This tells the run loop to stop scheduling the timer. The run loop will thus give up its strong pointer to this timer. If your pointer to the timer is weak, it will be set to nil at this point. This is nice because an invalidated timer like this is no longer of any use to you. Tolerance It might help system performance to set a tolerance for late firing. For example, if you have timer that goes off once a minute, a tolerance of 10s might be fine. myoneminutetimer.tolerance = 10 // in seconds The firing time is relative to the start of the timer (not the last time it fired), i.e. no drift.

NSTimer Demo Blinking FaceIt

Kinds of Animation Animating UIView properties Changing things like the frame or transparency. Animating Controller transitions (as in a UINavigationController) Beyond the scope of this course, but fundamental principles are the same. Core Animation Underlying powerful animation framework (also beyond the scope of this course). OpenGL and Metal 3D SpriteKit 2.5D animation (overlapping images moving around over each other, etc.) Dynamic Animation Physics -based animation.

UIView Animation Changes to certain UIView properties can be animated over time frame/center transform (translation, rotation and scale) alpha (opacity) backgroundcolor Done with UIView class method(s) using closures The class methods takes animation parameters and an animation block as arguments. The animation block contains the code that makes the changes to the UIView(s). The changes inside the block are made immediately (even though they will appear over time ). Most also have another completion block to be executed when the animation is done.

UIView Animation Animation class method in UIView class func animate(withduration: TimeInterval, delay: TimeInterval, options: UIViewAnimationOptions, animations: () -> Void, completion: ((finished: Bool) -> Void)?)

Example if myview.alpha == 1.0 { UIView Animation UIView.animate(withDuration: 3.0, delay: 2.0, options: [.curvelinear], animations: { myview.alpha = 0.0 }, completion: { if $0 { myview.removefromsuperview() } }) print( myview.alpha = \(myview.alpha) ) } This would cause myview to fade out over 3 seconds (starting 2s from now). Then it would remove myview from the view hierarchy (but only if the fade completed). If, within the 5s, someone animated the alpha to non-zero, the removal would not happen. The output on the console would be myview.alpha = 0.0 even though the alpha on the screen won t be zero for 5 more seconds!

UIViewAnimationOptions beginfromcurrentstate allowuserinteraction layoutsubviews repeat autoreverse overrideinheritedduration overrideinheritedcurve allowanimatedcontent curveeaseineaseout curveeasein curvelinear UIView Animation // pick up from other, in-progress animations of these properties // allow gestures to get processed while animation is in progress // animate the relayout of subviews with a parent s animation // repeat indefinitely // play animation forwards, then backwards // if not set, use duration of any in-progress animation // if not set, use curve (e.g. ease-in/out) of in-progress animation // if not set, just interpolate between current and end bits // slower at the beginning, normal throughout, then slow at end // slower at the beginning, but then constant through the rest // same speed throughout

UIView Animation Sometimes you want to make an entire view modification at once In this case you are not limited to special properties like alpha, frame and transform Flip the entire view over UIViewAnimationOptions.transitionFlipFrom{Left,Right,Top,Bottom} Dissolve from old to new state.transitioncrossdissolve Curling up or down.transitioncurl{up,down} Use closures again with this UIView class method UIView.transition(with: UIView, duration: TimeInterval, options: UIViewAnimationOptions, animations: () -> Void, completion: ((finished: Bool) -> Void)?)

UIView Animation Example Flipping a playing card over UIView.transition(with: myplayingcardview, duration: 0.75, options: [.transitionflipfromleft], animations: { cardisfaceup =!cardisfaceup } completion: nil) Presuming myplayingcardview draws itself face up or down depending on cardisfaceup This will cause the card to flip over (from the left edge of the card)

UIView Animation Animating changes to the view hierarchy is slightly different In other words, you want to animate the adding/removing of subviews (or (un)hiding them) UIView.transition(from: UIView, to: UIView, duration: TimeInterval, options: UIViewAnimationOptions, completion: ((finished: Bool) -> Void)?) UIViewAnimationOptions.showHideTransitionViews if you want to use the hidden property. Otherwise it will actually remove fromview from the view hierarchy and add toview.

View Animation Demos Smoother blinking in FaceIt Head shake in FaceIt

Dynamic Animation A little different approach to animation than UIView-based Set up physics relating animatable objects and let them run until they resolve to stasis. Easily possible to set it up so that stasis never occurs, but that could be performance problem. Steps Create a UIDynamicAnimator Add UIDynamicBehaviors to it (gravity, collisions, etc.) Add UIDynamicItems (usually UIViews) to the UIDynamicBehaviors (UIDynamicItem is an protocol which UIView happens to implement) That s it! Things will instantly start animating!

Create a UIDynamicAnimator Dynamic Animation var animator = UIDynamicAnimator(referenceView: UIView) If animating views, all views must be in a view hierarchy with referenceview at the top. Create and add UIDynamicBehavior instances e.g., let gravity = UIGravityBehavior() animator.addbehavior(gravity) e.g., collider = UICollisionBehavior() animator.addbehavior(collider)

Dynamic Animation Add UIDynamicItems to a UIDynamicBehavior let item1: UIDynamicItem =... // usually a UIView let item2: UIDynamicItem =... // usually a UIView gravity.additem(item1) collider.additem(item1) gravity.additem(item2) item1 and item2 will both be affect by gravity item1 will collide with collider s other items or boundaries, but not with item2

Dynamic Animation UIDynamicItem protocol Any animatable item must implement this protocol UIDynamicItem { } var bounds: CGRect { get } var center: CGPoint { get set } var transform: CGAffineTransform { get set } // note that the size cannot be animated // but the position can // and so can the rotation UIView implements this protocol If you change center or transform while the animator is running, you must call this method in UIDynamicAnimator func updateitemusingcurrentstate(item: UIDynamicItem)

UIGravityBehavior var angle: CGFloat var magnitude: CGFloat UIAttachmentBehavior Behaviors // in radians; 0 is to the right; positive numbers are counter-clockwise // 1.0 is 1000 points/s/s init(item: UIDynamicItem, attachedtoanchor: CGPoint) init(item: UIDynamicItem, attachedto: UIDynamicItem) init(item: UIDynamicItem, offsetfromcenter: CGPoint, attachedto[anchor] ) var length: CGFloat // distance between attached things (this is settable while animating!) var anchorpoint: CGPoint // can also be set at any time, even while animating The attachment can oscillate (i.e. like a spring) and you can control frequency and damping

UICollisionBehavior Behaviors var collisionmode: UICollisionBehaviorMode //.items,.boundaries, or.everything If.Items, then any items you add to a UICollisionBehavior will bounce off of each other If.Boundaries, then you add UIBezierPath boundaries for items to bounce off of func addboundary(withidentifier: NSCopying, for: UIBezierPath) func addboundary(withidentifier: NSCopying, from: CGPoint, to: CGPoint) func removeboundary(withidentifier: NSCopying) var translatesreferenceboundsintoboundary: Bool // referenceview s edges NSCopying means NSString or NSNumber, but remember you can as to String, Int, etc.

Behaviors UICollisionBehavior How do you find out when a collision happens? var collisiondelegate: UICollisionBehaviorDelegate this delegate will be sent methods like func collisionbehavior(behavior: UICollisionBehavior, began/endedcontactfor: UIDynamicItem, withboundaryidentifier: NSCopying at: CGPoint) // with:uidynamicitem too The withboundaryidentifier is the one you pass to addboundary(withidentifier:).

UISnapBehavior Behaviors init(item: UIDynamicItem, snapto: CGPoint) Imagine four springs at four corners around the item in the new spot. You can control the damping of these four springs with var damping: CGFloat UIPushBehavior var mode: UIPushBehaviorMode var pushdirection: CGVector or var angle: CGFloat // in radians and //.continuous or.instantaneous var magnitude: CGFloat // magnitude 1.0 moves a 100x100 view at 100 pts/s/s Interesting aspect to this behavior If you push.instantaneous, what happens after it s done? It just sits there wasting memory. We ll talk about how to clear that up in a moment.

Behaviors UIDynamicItemBehavior Sort of a special meta behavior. Controls the behavior of items as they are affected by other behaviors. Any item added to this behavior (with additem) will be affected by var allowsrotation: Bool var friction: CGFloat var elasticity: CGFloat and others, see documentation. Can also get information about items with this behavior... func linearvelocity(for: UIDynamicItem) -> CGPoint func addlinearvelocity(cgpoint, for: UIDynamicItem) func angularvelocity(for: UIDynamicItem) -> CGFloat Multiple UIDynamicItemBehaviors affecting the same item(s) is advanced (not for you!)

Behaviors UIDynamicBehavior Superclass of behaviors. You can create your own subclass which is a combination of other behaviors. Usually you override init method(s) and additem and removeitem to call func addchildbehavior(uidynamicbehavior) This is a good way to encapsulate a physics behavior that is a composite of other behaviors. You might also have some API which helps your subclass configure its children. All behaviors know the UIDynamicAnimator they are part of They can only be part of one at a time. var dynamicanimator: UIDynamicAnimator? { get } And the behavior will be sent this message when its animator changes func willmove(to: UIDynamicAnimator?)

Behaviors UIDynamicBehavior s action property Every time the behavior acts on items, this block of code that you can set is executed var action: (() -> Void)? (i.e. it s called action, it takes no arguments and returns nothing) You can set this to do anything you want. But it will be called a lot, so make it very efficient. If the action refers to properties in the behavior itself, watch out for memory cycles.

Stasis UIDynamicAnimator s delegate tells you when animation pauses Just set the delegate var delegate: UIDynamicAnimatorDelegate and you ll find out when stasis is reached and when animation will resume func dynamicanimatordidpause(uidynamicanimator) func dynamicanimatorwillresume(uidynamicanimator)

Memory Cycle Avoidance Example of using action and avoiding a memory cycle Let s go back to the case of a.instantaneous UIPushBehavior When it is done acting on its items, it would be nice to remove it from its animator We can do this with the action method, but we must be careful to avoid a memory cycle if let pushbehavior = UIPushBehavior(items: [ ], mode:.instantaneous) { } pushbehavior.magnitude = pushbehavior.angle = pushbehavior.action = { } pushbehavior.dynamicanimator!.removebehavior(pushbehavior) animator.addbehavior(pushbehavior) // will push right away The above has a memory cycle because its action captures a pointer back to itself So neither the action closure nor the pushbehavior can ever leave the heap

Memory Cycle Avoidance Example of using action and avoiding a memory cycle Let s go back to the case of a.instantaneous UIPushBehavior When it is done acting on its items, it would be nice to remove it from its animator We can do this with the action method, but we must be careful to avoid a memory cycle if let pushbehavior = UIPushBehavior(items: [ ], mode:.instantaneous) { } pushbehavior.magnitude = pushbehavior.angle = pushbehavior.action = { [unowned pushbehavior] in } pushbehavior.dynamicanimator!.removebehavior(pushbehavior) animator.addbehavior(pushbehavior) // w ill pu sh r ig ht away Now it no longer captures pushbehavior This is safe to mark unowned because if the action closure exists, so does the pushbehavior When the pushbehavior removes itself from the animator, the action won t keep it in memory So they ll both leave the heap because the animator no longer points to the behavior