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

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

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. Spring CS193p. Spring 2016

View Hierarchy - UIWindow

Today s Topics. Views Drawing Text & Images Animation

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

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

Views. A view (i.e. UIView subclass) represents a rectangular area Defines a coordinate space

CS193p Spring 2010 Monday, April 12, 2010

Science. Computer Science

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

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

ios Mobile Development

Core Graphics & Animation. ios App Development Fall 2010 Lecture 17

COMP327 Mobile Computing. Lecture Set 9 - Model, View, Controller

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

Views, Drawing, and Events. Lecture 5

Announcements. Lab 3. Lab 2 is due on Monday Sept 21 st. Lab 3 is posted Due September 30 th

The Best of Both Worlds: Using UIKit with OpenGL

lecture 10 UI/UX and Programmatic Design cs : spring 2018

Developing Applications for ios

View Concepts. iphone Application Programming Lecture 4: User Interface Design. SDK provide many types of Views to show your content

Adopting Advanced Features of the New UI

Custom Views and Events. Lecture 7

View Controller Lifecycle

User Experience: Windows & Views

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

Developing Applications for ios

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

ios Memory Deep Dive #WWDC18 Kyle Howarth, Software Engineer James Snee, Software Engineer Kris Markel, Software Engineer

EXERCISES RELATED TO ios PROGRAMMING

Apple introduced MapKit with ios, maps were based on Google.

Graphics & Animation: 2D Drawing

Graphics and Animation on ios

ITP 342 Mobile App Dev. Animation

Metal. GPU-accelerated advanced 3D graphics rendering and data-parallel computation. source rebelsmarket.com

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

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

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

Lecture 5 Demo Code: FaceIt MVC and Gestures

Mobile Application Programming. Controls

Assignment III: Graphing Calculator

As you convert your QuickDraw application to one that uses only Quartz, there are two primary issues you ll face with respect to PICT data:

Output models Drawing Rasterization Color models

Modern User Interaction on ios

Praktikum Entwicklung von Mediensystemen mit ios

ITP 342 Mobile App Dev. Animation

CUSTOM VIEWS. The View Hierarchy. Chapter 12

Praktikum Entwicklung von Mediensystemen mit

iphone Application Programming Lecture 5: View Programming

Swift API Design Guidelines

Getting the Most out of Playgrounds in Xcode

Editing Media with AV Foundation

CS193P - Lecture 8. iphone Application Development. Scroll Views & Table Views

Assignment III: Graphing Calculator

Lecture 11: Output 2. Fall UI Design and Implementation 1

Developing Applications for ios

Leveraging Touch Input on ios

Custom Views and Drawing. Lecture 5

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

SFU CMPT 361 Computer Graphics Fall 2017 Assignment 2. Assignment due Thursday, October 19, 11:59pm

What s New in imessage Apps

LESSONS LEARNED. SWIFT. Dagna Bieda, 7th April 2016

Developing Core Image Filters for ios

Scalable Vector Graphics (SVG) vector image World Wide Web Consortium (W3C) defined with XML searched indexed scripted compressed Mozilla Firefox

Building GUIs with UIKit. Kevin Cathey

A Vertical Slider for iphone

Today s Topics. Scroll views Table views. UITableViewController Table view cells. Displaying data Controlling appearance & behavior

For each question, indicate whether the statement is true or false by circling T or F, respectively.

let w = UIWindow(frame: UIScreen.mainScreen().bounds)

CHAPTER 1 Graphics Systems and Models 3

Scroll View School Hands-On Challenges

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

Building Visually Rich User Experiences

Patterns & practices for unit-testing Swift-ly. Jakub Turek 18th June, 2018

CSC 581: Mobile App Development Spring 2018

Improving your Existing Apps with Swift

(a) rotating 45 0 about the origin and then translating in the direction of vector I by 4 units and (b) translating and then rotation.

Apple Development Technology Workshops

Praktikum Entwicklung von Mediensystemen mit ios

Assignment III: Graphing Calculator

2D/3D Geometric Transformations and Scene Graphs

AUTO LAYOUT IS A UNICORN

Core Animation. Building Animated UI s. Bill Dudney. Gala Factory Software LLC. Bill Dudney Core Animation: Building Animated UI s Slide 1

Scene Graphs. CS4620/5620: Lecture 7. Announcements. HW 1 out. PA 1 will be out on Wed

EXAMINATIONS 2016 TRIMESTER 2

Mobile Application Programming. Layout Techniques

CS 465 Program 4: Modeller

OVERVIEW. Why learn ios programming? Share first-hand experience. Identify platform differences. Identify similarities with.net

Assignment III: Graphing Calculator

What s New in Core Image

From the dock at the left, right, top, or bottom of your monitor screen, open the Finder.

Transformation Hierarchies. CS 4620 Lecture 5

UICollectionView. NSCoder Milwaukee. 2 April John Psuik. Tuesday, April 2, 13

Lecture 08: Hierarchical Modeling with Scene Graphs

Developing Applications for ios

Affine Transformations. Transforming shape models Combining affine transformations Scene graphs, interactor trees Hit tests on transformed shapes

OpenGL ES for iphone Games. Erik M. Buck

Transcription:

Custom Drawing & Animation CS 442: Mobile App Development Michael Saelee <lee@iit.edu>

Frameworks - UIKit - Core Graphics / Quartz - Core Animation - OpenGL ES

UIKit OpenGL ES Core Graphics Core Animation

UIKit (mostly) Swift/ObjC API UI... classes/functions

UIKit Base view class: UIView Pre-built controls: UIControls

UIKit typically, use concrete subclasses as is (no need to subclass) e.g., UILabel, UIButton, UITableView, UIImageView

UIKit can also subclass UIView to draw custom UI elements

UIKit support for - 2D drawing - transformations - predefined transitions - basic animation

CG aka Quartz 2D C API for drawing

CG support for: - layer-based graphics - patterns, gradients, etc. - color spaces - working with bitmaps

CG mostly, UIKit draws using CG i.e., more than one way of doing anything

UIKit CG // clear with white rectangle UIColor.whiteColor().set() UIRectFill(CGRect(x: 0, y: 0, width: 100, height: 100)) // load and draw image at (0,0) UIImage(named: image.png")?.drawatpoint(cgpoint(x: 0, y: 0)) // get current graphics context to draw into CGContextRef context = UIGraphicsGetCurrentContext(); // clear with white rectangle CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0); CGContextFillRect(context, self.bounds); // load image from file CGDataProviderRef provider = CGDataProviderCreateWithFilename(imageFileName); CGImageRef image = CGImageCreateWithPNGDataProvider(provider, NULL, true, kcgrenderingintentdefault); CGDataProviderRelease(provider); // draw image at (0,0) CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image)), image); CGImageRelease(image);

CA API for animation and compositing verb [ trans. ] [usu. as n. ] ( compositing) combine (two or more images) to make a single picture, esp. electronically : photographic compositing by computer.

all UIViews are backed by CA layers CA

CA can create a hierarchy of CALayers within a single view (in addition to creating a hierarchy of views)

CA generally, layers are: - more lightweight - more flexible - more complex

CA CALayer properties can be automatically animated

CA support for: - simple value interpolation - key frame animation - transition effects - animation groups

UIKit CA // load image and add to view at position (100,100) let imageview = UIImageView(image: UIImage(named: "image.png")) imageview.center = CGPoint(x: 100, y: 100) view.addsubview(imageview) // animate using a block -- bounce between start position and (300,300) UIView.animateWithDuration(5.0, delay: 0.0, options:.repeat.autoreverse, animations: { view.center = CGPoint(x: 300, y: 300) }, completion: nil) // create new CA layer and populate with image CALayer *layer = [CALayer layer]; UIImage *image = [UIImage imagenamed:@"image.png"]; layer.contents = image.cgimage; layer.frame = CGRectMake(0, 0, image.size.width, image.size.height); // add layer to view layer [self.view.layer addsublayer:layer]; // create basic animation to interpolate position between (100,100) and (300,300) CABasicAnimation *anim = [CABasicAnimation animationwithkeypath:@"position"]; anim.fromvalue = [NSValue valuewithcgpoint:cgpointmake(100, 100)]; anim.tovalue = [NSValue valuewithcgpoint:cgpointmake(300, 300)]; anim.duration = 5.0; anim.autoreverses = YES; anim.repeatcount = HUGE_VALF; anim.timingfunction = [CAMediaTimingFunction functionwithname:kcamediatimingfunctioneaseineaseout]; [layer addanimation:anim forkey:@"backandforth"];

industry standard 2D/3D graphics API OpenGL

OpenGL technically, OpenGL ES; i.e., for Embedded Systems

OpenGL OpenGL ES 2.0 not backwards compatible (fixed-function vs. shaders)

OpenGL hardware acceleration ipad 2: CPUx2, GPUx9, ipad 3: CPUx1, GPUx2-3, etc.

OpenGL OpenGL render destination: CAEAGLLayer in UIView

OpenGL generally, don t mix OpenGL and UIKit/CA/CG functions (e.g., no layer transforms)

UIKit OpenGL ES Core Graphics Core Animation

Drawing

(0,0) x 320 y 480 ULO

(0,0) x 480 y 320 ULO

320 x 480 points (not necessarily = pixels!)

resolution independence scale factor points = pixels (retina display: scale = 2.0)

principal data types: CGPoint, CGSize, CGRect /* Points. */ struct CGPoint { var x: CGFloat var y: CGFloat } /* Sizes. */ struct CGSize { var width: CGFloat var height: CGFloat } /* Rectangles. */ struct CGRect { var origin: CGPoint var size: CGSize }

/* Return the left/mid/right x-value of rect. */ CGFloat CGRectGetMinX(CGRect rect); CGFloat CGRectGetMidX(CGRect rect); CGFloat CGRectGetMaxX(CGRect rect); /* Return the top/mid/bottom y-value of rect. */ CGFloat CGRectGetMinY(CGRect rect); CGFloat CGRectGetMidY(CGRect rect); CGFloat CGRectGetMaxY(CGRect rect); /* Return the width/height of rect. */ CGFloat CGRectGetWidth(CGRect rect); CGFloat CGRectGetHeight(CGRect rect); /* Standardize rect -- i.e., convert it to an equivalent rect which has positive width and height. */ CGRect CGRectStandardize(CGRect rect); /* Return true if rect is empty (that is, if it has zero width or height), false otherwise. A null rect is defined to be empty. */ bool CGRectIsEmpty(CGRect rect);

locating/placing things: frame & bounds rectangles

frame = origin & size in superview s coordinate system

bounds = origin & size in local view s coordinate system

application window

view frame: - origin = (6, 5) - size = (15, 10) view application window

view bounds: - origin = (0, 0) - size = (15, 10) subview frame: - origin = (3, 4) - size = (6, 5) subview view application window

size of frame, bounds are automatically linked

reposition view by changing frame origin or center (changing one automatically adjusts the other)

can change bounds origin to adjust local coordinate system

view bounds: - origin = (0, 0) - size = (15, 10) subview frame: - origin = (3, 4) - size = (6, 5)

view bounds: - origin = (1, 1) - size = (15, 10) subview frame: - origin = (3, 4) - size = (6, 5)

view bounds: - origin = (-1, 4) - size = (15, 10) subview frame: - origin = (3, 4) - size = (6, 5)

/* Fill `rect' with solid color */ void UIRectFill(CGRect rect); void UIRectFillUsingBlendMode(CGRect rect, CGBlendMode blendmode); /* Draw 1px frame inside `rect'. */ void UIRectFrame(CGRect rect); void UIRectFrameUsingBlendMode(CGRect rect, CGBlendMode blendmode); Simple Drawing

@interface UIColor // Convenience methods for creating autoreleased colors + (UIColor *)colorwithred:(cgfloat)red green:(cgfloat)green blue:(cgfloat)blue alpha:(cgfloat)alpha; // Some convenience methods to create colors. These colors are cached. + (UIColor *)blackcolor; // 0.0 white + (UIColor *)redcolor; // 1.0, 0.0, 0.0 RGB + (UIColor *)greencolor; // 0.0, 1.0, 0.0 RGB + (UIColor *)bluecolor; // 0.0, 0.0, 1.0 RGB + (UIColor *)clearcolor; // 0.0 white, 0.0 alpha // Set the color: Sets the fill and stroke colors in the current drawing context. - (void)set; // Set the fill or stroke colors individually. - (void)setfill; - (void)setstroke; // Access the underlying CGColor @property(nonatomic,readonly) CGColorRef CGColor; @end Color?

UIKit framework always draws to implicit, current Graphics Context

// establish current drawing context (image buffer) UIGraphicsBeginImageContext(CGSize(width: 100, height: 100)) // clear background with white box UIColor.whiteColor().set() UIRectFill(CGRect(x: 0, y: 0, width: 100, height: 100)) // draw black frame UIColor.blackColor().set() UIRectFrame(CGRect(x: 0, y: 0, width: 100, height: 100)) // draw (filled) blue rectangle UIColor.blueColor().set() UIRectFill(CGRect(x: 10, y: 10, width: 80, height: 80)) // extract image from context let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext()

CG maintains a stack of graphics contexts (empty, by default)

UIView objects automatically push graphics contexts before calling drawrect:

@interface UIView(UIViewRendering) /* All custom drawing must happen from this method. Should limit drawing to rect -- on first call rect is usually equal to our bounds. */ - (void)drawrect:(cgrect)rect; /* drawrect: is called lazily. If view must be redrawn, we must notify the system by calling one of these methods below. */ - (void)setneedsdisplay; - (void)setneedsdisplayinrect:(cgrect)rect; @end

Q: draw in current view vs. adding subview? - it depends - subviews allow us to add/remove objects - but adds memory + processing overhead

HelloWorldView discuss root view frame origin/size Rectangle1 using setneedsdisplay to force refresh Rectangle2 use multiple views to track drawn rectangles ignore contentstretch for now GameBoard - handling demo

subview size > superview?

default: container views don t clip subviews but no scrolling, either - to implement, parent may adjust its own bounds to move children into view - or, alternatively, change all child frames (much messier!)

Clipping Demo - effect of clipstobounds ScrollView Demo automatic pan support based on contentsize also: pinch to zoom demo

view transformations: translating, scaling, rotating

common strategy: - draw unit object at (0,0) - translate, scale, rotate to final position/size/orientation

drawrect: can be very lazy i.e., draw once, transform many times

implementation: affine transform matrices

transformed coordinates x 0 y 0 1 = x y 1 transformation matrix 2 4 original coordinates a b 0 c d 0 t x t y 1 3 5 x 0 = ax + cy + t x y 0 = bx + dy + t y e.g. x 0 y 0 1 = x y 1 2 4 = x + t x y + t y 1 1 0 0 0 1 0 t x t y 1 3 5

struct CGAffineTransform { CGFloat a, b, c, d; CGFloat tx, ty; } /* The identity transform: [ 1 0 0 1 0 0 ]. */ extern const CGAffineTransform CGAffineTransformIdentity; /* Return a transform which translates by `(tx, ty)': t' = [ 1 0 0 1 tx ty ] */ CGAffineTransform CGAffineTransformMakeTranslation(CGFloat tx, CGFloat ty); /* Return a transform which scales by `(sx, sy)': t' = [ sx 0 0 sy 0 0 ] */ CGAffineTransform CGAffineTransformMakeScale(CGFloat sx, CGFloat sy); /* Return a transform which rotates by `angle' radians: t' = [ cos(angle) sin(angle) -sin(angle) cos(angle) 0 0 ] */ CGAffineTransform CGAffineTransformMakeRotation(CGFloat angle) /* Concatenate translation, scaling, rotation transforms to existing matrices. */ CGAffineTransform CGAffineTransformTranslate(CGAffineTransform t, CGFloat tx, CGFloat ty); CGAffineTransform CGAffineTransformScale(CGAffineTransform t, CGFloat sx, CGFloat sy); CGAffineTransform CGAffineTransformRotate(CGAffineTransform t, CGFloat angle);

for given graphics context (e.g., in drawrect:), change current transform matrix (CTM)

/* Scale the current graphics state's transformation matrix (the CTM) by `(sx, sy)'. */ void CGContextScaleCTM(CGContextRef c, CGFloat sx, CGFloat sy); /* Translate the current graphics state's transformation matrix (the CTM) by `(tx, ty)'. */ void CGContextTranslateCTM(CGContextRef c, CGFloat tx, CGFloat ty); /* Rotate the current graphics state's transformation matrix (the CTM) by `angle' radians. */ void CGContextRotateCTM(CGContextRef c, CGFloat angle); /* Concatenate the current graphics state's transformation matrix (the CTM) with the affine transform `transform'. */ void CGContextConcatCTM(CGContextRef c, CGAffineTransform transform);

ExpandingFrame look at RotatingView drawrect motivate CGContextSave/RestoreGState explore frame/bounds relationship demo

cubic & quadratic Bézier curves Drawing Other Shapes

@interface UIBezierPath : NSObject<NSCopying, NSCoding> { + (UIBezierPath *)bezierpath; - (void)movetopoint:(cgpoint)point; - (void)addlinetopoint:(cgpoint)point; - (void)addcurvetopoint:(cgpoint)endpoint controlpoint1:(cgpoint)controlpoint1 controlpoint2:(cgpoint)controlpoint2; - (void)addquadcurvetopoint:(cgpoint)endpoint controlpoint:(cgpoint)controlpoint; - (void)addarcwithcenter:(cgpoint)center radius:(cgfloat)radius startangle:(cgfloat)startangle endangle:(cgfloat)endangle clockwise:(bool)clockwise; - (void)closepath; + (UIBezierPath *)bezierpathwithrect:(cgrect)rect; + (UIBezierPath *)bezierpathwithovalinrect:(cgrect)rect; + (UIBezierPath *)bezierpathwithroundedrect:(cgrect)rect cornerradius:(cgfloat)cornerradius; @property(nonatomic) CGPathRef CGPath; @end

Bézier curves can be created, stored, and reused, independent of graphics context

BezierDrawing demo

rects, curves, etc. = vector graphics infinite scaleability

raster graphics? e.g., bitmaps, JPG, PNG

UIKit: load with UIImage

imagenamed: Returns the image object associated with the specified filename. + (UIImage *)imagenamed:(nsstring *)name Parameters name The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application s main bundle. Return Value The image object for the specified file, or nil if the method could not find the specified image. Discussion This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object. On a device running ios 4 or later, the behavior is identical if the device s screen has a scale of 1.0. If the screen has a scale of 2.0, this method first searches for an image file with the same filename with an @2x suffix appended to it. For example, if the file s name is button, it first searches for button@2x. If it finds a 2x, it loads that image and sets the scale property of the returned UIImage object to 2.0. Otherwise, it loads the unmodified filename and sets the scale property to 1.0.

caveat emptor: imagenamed cache can be quite aggressive! (Google: imagenamed cache )

raster graphics problem: scaling pixelation

UIView contentstretch property defines which parts of an image are stretched

ContentStretching demo

image = UIImage(named:@"image.png") ➊ UIKit (subview) let imageview = UIImageView(image: image) view.addsubview(imageview) ➋ CG (drawing) func drawrect(rect: CGRect) { image.drawatpoint(cgpoint(x: 0, y: 0)) } ➌ CA (compositing) let layer = CALayer() layer.contents = image.cgimage view.layer.addsublayer(layer) Image Drawing Options

ImageDrawing run all three versions (view, layer, drawrect) --- may want to keep num_image < 100 for the last run through instruments: memory allocations (num_images=10000 for view, layer version), and time profiler (esp. interesting for drawrect based) demo

more reading (Xcode library): - View Programming Guide for ios - Quartz 2D Programming Guide

Animation

UIKit / CoreAnimation

typically, use magic UIView / CALayer animation mechanism

i.e., provide new view properties in animation block along with time frame core animation does the rest

note: CA updates happen in a separate thread!

animated parameters are updated according to a specified interpolation curve (aka timing function)

timing functions