SlideShare a Scribd company logo
@bobmccune
Bob McCune
Quartz 2D
with Swift 3
-Overview of the Quartz framework
- What is it?
- When do you need it?
-Core capabilities of framework:
- Contexts and Paths
- Drawing lines, curves, and images
- Applying transformations
-Recipes and Examples
Agenda
What will I learn?
What is Quartz?
-Apple’s 2D drawing framework based on the PDF imaging model
-Graphics API to produce lines, curves, transforms, gradients, etc.
-Uses painters model for drawing operations
What is Quartz 2D?
Wasn’t this supposed to be about Core Graphics?
Drawing Order Result
-Prefer to build your UI using images
- Better performance and caching
- Easier to create and maintain
- Keeps your graphics designers employed
-It’s best to design your UI using images…
When do I need it?
Isn’t this what graphics designers are for?
...until you can’t
Getting Started
Objective-C
CGContext *context = [[CGContext alloc] init];
[context moveToPoint:CGPointMake(12.0f, 12.0f)];
[context addLineToPoint:CGPointMake(24.0f, 24.0f)];
[context fill];
Understanding the Syntax
Dude, where’s my objects?
Understanding the Syntax
Dude, where’s my objects?
Objective-C
CGContext *context = [[CGContext alloc] init];
[context moveToPoint:CGPointMake(12.0f, 12.0f)];
[context addLineToPoint:CGPointMake(24.0f, 24.0f)];
[context fill];
Standard C
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, 12.0f, 12.0f);
CGContextAddLineToPoint(context, 24.0f, 24.0f);
CGContextFillPath(context);
Quartz not an Objective-C API
Understanding the Syntax
Dude, where’s my objects?
Standard C
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, 12.0f, 12.0f);
CGContextAddLineToPoint(context, 24.0f, 24.0f);
CGContextFillPath(context);
Swift 2
let context = UIGraphicsGetCurrentContext()!
CGContextMoveToPoint(context, 12.0, 12.0)
CGContextAddLineToPoint(context, 24.0, 24.0)
CGContextFillPath(context)
Understanding the Syntax
Dude, where’s my objects?
Swift 3
let context = UIGraphicsGetCurrentContext()!
context.move(to: CGPoint(x: 12.0, y: 12.0))
context.addLine(to: CGPoint(x: 24.0, y: 24.0))
context.fillPath()
Swift 2
let context = UIGraphicsGetCurrentContext()!
CGContextMoveToPoint(context, 12.0, 12.0)
CGContextAddLineToPoint(context, 24.0, 24.0)
CGContextFillPath(context)
Session 403: Swift API Design Guidelines (WWDC 2016)
Graphics Contexts
-Graphics context provides the drawing area
-Manages core drawing states:
- Colors, line widths, transforms, etc.
- It’s a state machine
-Key Quartz Contexts:
- CGContext
- CGBitmapContext
- CGPDFContext
Quartz Graphics Contexts
The Canvas
-Current Transformation Matrix (CTM) defines the coordinate system
-Coordinate system varies on macOS and iOS/tvOS
Quartz Coordinate System
Drawing Orientation
0, 0
y
x
Positive 0, 0
y
x
Positive
macOS iOS and tvOS
-Drawing is defined in terms
of points
-Points are abstract,
infinitely thin
-Points live in User Space
CGContext Drawing
Quartz Points
p0
p1
Points are Device-Independent
Think in points not pixels
H: 70 L:46
Sunny
Cupertino
66
p0
p1
-CGContext is the default drawing context
- Created by UIKit and AppKit
-Get a reference to it:
CGContext Drawing
CGContext
let context = UIGraphicsGetCurrentContext()
iOS and tvOS
let context = NSGraphicsContext.current()?.graphicsPort
macOS
Getting Started
Where do I draw?
Getting Started
Where do I draw?
Getting Started
Where do I draw?
Getting Started
Where do I draw?
class HelloQuartzViewController: UIViewController {
func drawBackground(recognizer: UIGestureRecognizer) {
}
}
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(randomColor())
context?.fill(view.bounds)
Getting Started
Where do I draw?
class HelloQuartzView: UIView {
override func draw(_ rect: CGRect) {
}
}
class HelloQuartzViewController: UIViewController {
func drawBackground(recognizer: UIGestureRecognizer) {
}
}
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(randomColor())
context?.fill(view.bounds)
Getting Started
Where do I draw?
class HelloQuartzView: UIView {
override func draw(_ rect: CGRect) {
}
}
class HelloQuartzViewController: UIViewController {
func drawBackground(recognizer: UIGestureRecognizer) {
}
}
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(randomColor())
context?.fill(view.bounds)
// Trigger call to HelloQuartzView's draw(:) method
helloView.setNeedsDisplay()
Basic Paths
CGContext Drawing
Defining Paths
(0, 0)
(100, 100)
let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
context.addRect(rect)
CGContext Drawing
Defining Paths
(0, 0)
(100, 100)
let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
context.addEllipse(in: rect)
CGContext Drawing
Defining Paths
(0, 0)
(100, 100)
context.setStrokeColor(white)
context.drawPath(using: .stroke)
CGContext Drawing
Defining Paths
(0, 0)
(100, 100)
context.setFillColor(yellow)
context.drawPath(using: .fill)
CGContext Drawing
Defining Paths
(0, 0)
(100, 100)
context.drawPath(using: .fillStroke)
-Colors must be defined on the context before drawing
-Fill Colors
- setFillColor(color: CGColor)
- setFillColor(gray: CGFloat, alpha: CGFloat)
- setFillColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
-Stroke Colors
- setStrokeColor(color: CGColor)
- setStrokeColor(gray: CGFloat, alpha: CGFloat)
- setStrokeColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
Defining Colors
CGColor
- CGColor is the native Quartz color type
- UIColor is the native UIKit color type
-Use UIColor in almost all cases
- Easier to create
- Named color initializers
- Easy to convert to and from CGColor
Defining Colors
CGColor vs UIColor
// Convert to Quartz Type
let cgColor = UIColor.red.cgColor
context.setFillColor(cgColor)
// Convert to UIKit Type
let uiColor = UIColor(cgColor: cgColor)
-Lines are the most essential primitive
-Lines are always defined by their endpoints
-Basic Recipe:
1. Begin a new path
2. Move to initial starting point
3. Add lines defining shape
4. Close the path (optional)
5. Draw Path
Drawing Lines
Defining Paths
CGContext Drawing
Constructing Paths
context.beginPath()
context.move(to: .zero)
CGContext Drawing
Constructing Paths
context.addLine(to: CGPoint(x: 0.0, y: 4.0))
Constructing Paths
CGContext Drawing
context.addLine(to: CGPoint(x: 4.0, y: 4.0))
CGContext Drawing
Constructing Paths
context.addLine(to: CGPoint(x: 4.0, y: 0.0))
CGContext Drawing
Constructing Paths
context.closePath()
CGContext Drawing
Constructing Paths
let whiteColor = UIColor.white
context.setFillColor(whiteColor.cgColor)
CGContext Drawing
Constructing Paths
context.drawPath(using: .fill)
Advanced Paths
-Arcs define circle segments
-Arcs are defined with the following:
- Center x, y coordinates
- Radius
- Start and stop angles (in radians)
- Direction (clockwise or counter-clockwise)
-Created using:
- addArc(center:radius:startAngle:endAngle:clockwise:)
- addArc(tangent1End:tangent2End:radius:)
Drawing Arcs
Constructing Paths
-Arc functions are not aware of flipped coordinate system
- Need to think upside down (or)
- Transform coordinate system before using
- UIBezierPath wraps Quartz GGPath functionality
- Access to underlying path with CGPath property
-Generally easier to use UIBezierPath on iOS and tvOS
- * In Swift 3, direct Quartz usages is very similar
UIBezierPath
More iOS/tvOS-friendly solution
Drawing Arcs
Defining Paths
let path = UIBezierPath(arcCenter: centerPoint, radius: radius,
startAngle: 0, endAngle: degreesToRadians(270.0),
clockwise: false)
path.addLine(to: centerPoint)
context.addPath(path.cgPath)
Quadratic Bézier Curves
Constructing Paths
p0
context.beginPath()
context.move(to: p0)
Quadratic Bézier Curves
Constructing Paths
p0
p1
cp
context.addQuadCurve(to: p1, control: controlPoint)
Quadratic Bézier Curves
Constructing Paths
p0
p1
cp
context.setLineWidth(2.0)
context.setStrokeColor(UIColor.green.cgColor)
context.strokePath()
Cubic Bézier Curves
Constructing Paths
p0
context.beginPath();
context.move(to: p0)
Cubic Bézier Curves
Constructing Paths
p0
cp1
p1
cp2
context.addCurve(to: p1,
control1: cp1,
control2: cp2)
Cubic Bézier Curves
Constructing Paths
p0
cp1
cp2
p1
-cp1
-cp2
let tx = CGAffineTransform(scaleX: -1, y: 1)
context.addCurve(to: p0,
control1: cp2.applying(tx),
control2: cp1.applying(tx))
Cubic Bézier Curves
Constructing Paths
p0
cp1
cp2
p1
cp1
-cp2
context.closePath()
context.setFillColor(UIColor.red.cgColor)
context.fillPath()
-Quartz uses fill rules to determine what’s inside and outside of a
path.
-Uses one of the following:
- Non-zero Winding Rule (Default)
- Even Odd Rule
Fill Rules
To fill, or not to fill
Transformations
-Affine transformations are essential to all graphics programming
regardless of platform
-Allow you to manipulate the coordinate system to translate,
scale, skew, and rotate
-Transform preserves collinearity of lines
Affine Transformations
Transforming the Coordinate System
X
-CTM can be modified with the following:
- translateBy(x:y:)
- scaleBy(x:y:)
- rotate(by:)
Current Transformation Matrix
Modifying the CTM
Translate
Moving the Origin Point
(0, 0)
(100, 100)
Translate
Moving the Origin Point
(0, 0)
(0, 0)
context.translateBy(x: 100, y: 100)
Scale
Scaling the Unit Size
(0, 0)
(200, 200)
Scale
Scaling the Unit Size
(0, 0)
(200, 200)
context.scaleBy(x: 2.0, y: 2.0)
Rotate
Rotating the Context
context.rotate(by: degreesToRadians(15))
Gradients
-A gradient is a fill that varies from one color to another
-Quartz supports two different gradient types
- Linear varies between two endpoints
- Radial varies between two radial endpoints
Gradients
Drawing Gradients
Linear Radial
-Gradients can be created using either:
- init(colorsSpace:colors:locations:)
- init(colorSpace:colorComponents:locations:)
-Both functions require the following:
- CGColorSpace
- Colors (components or array of CGColor)
- Array of CGFloat values defining gradient color stops
Creating a CGGradient
CGGradient
CGGradientRef
Building the gradient code
let startColor = UIColor.red
let endColor = UIColor.orange
let colors = [startColor.cgColor, endColor.cgColor] as CFArray
let locations: [CGFloat] = [0, 1]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let gradient =
CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations)!
let startPoint = CGPoint(x: rect.midX, y: rect.minY)
let endPoint = CGPoint(x: rect.midX, y: rect.maxY)
let opts = CGGradientDrawingOptions()
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: opts)
Gradient Examples
Images
-Quartz has broad support for images
-Represented as CGImage
-Can be drawn using:
- draw(image:rect:)
- draw(image:rect:byTiling)
- CGBitmapContext allows for dynamically building image data
Working with Images
CGImage
-Don’t draw in Quartz. Use UIImageView.
-Choose UIImage over CGImage
- Easier to load and cache image content
- Provides methods for drawing
- Is aware flipped coordinate system
- UIImage provides a CGImage property
-Use CGImage for more advanced cases
- Cropping, scaling, masking
- Dynamic image creation
CGImage vs UIImage
Which should I use?
Using Image Masks
Hiding behind a mask
Using Image Masks
Hiding behind a mask
// Mask image created by toMask() extension
guard let maskImage = UIImage(named: “round_mask")?.cgImage?.toMask() else { return }
guard let jeffersonImage = UIImage(named: "jefferson")?.cgImage else { return }
if let masked = jeffersonImage.masking(maskImage) {
// Draw shadow to offset from background
let shadowOffset = CGSize(width: 1, height: 1)
let shadowColor = UIColor.darkGray.cgColor
context.setShadow(offset: shadowOffset, blur: 12, color: shadowColor)
let maskedImage = UIImage(cgImage: masked)
maskedImage.draw(in: drawingRect(for: maskedImage))
}
Cropping Images
cropping(to:)
let albumImage = UIImage(named: "vh1")!
let cropRect = CGRect(x: 20, y: 20, width: 200, height: 200)
if let cgImage = albumImage.cgImage?.cropping(to: cropRect) {
// Create new UIImage and use as needed
let eddieImage = UIImage(cgImage: cgImage)
}
-Quartz is a powerful drawing engine for Apple platforms
-Essential skill to master to build beautiful apps
-Quartz + Swift 3 = Awesome
Summary
Resources
Quartz 2D Programming Guide
http://developer.apple.com/
Programming with Quartz
David Gelphman
Bunny Laden

More Related Content

What's hot

"The 5 Personas of Product Management (and How to Hire for Them)" by Jason Shen
"The 5 Personas of Product Management (and How to Hire for Them)" by Jason Shen"The 5 Personas of Product Management (and How to Hire for Them)" by Jason Shen
"The 5 Personas of Product Management (and How to Hire for Them)" by Jason Shen
Productized
 
Low-level Shader Optimization for Next-Gen and DX11 by Emil Persson
Low-level Shader Optimization for Next-Gen and DX11 by Emil PerssonLow-level Shader Optimization for Next-Gen and DX11 by Emil Persson
Low-level Shader Optimization for Next-Gen and DX11 by Emil Persson
AMD Developer Central
 
Visible surface detection in computer graphic
Visible surface detection in computer graphicVisible surface detection in computer graphic
Visible surface detection in computer graphicanku2266
 
WkWebViewのキャッシュについて調べた
WkWebViewのキャッシュについて調べたWkWebViewのキャッシュについて調べた
WkWebViewのキャッシュについて調べた
firewood
 
「ユニティちゃんを踊らせよう!」モーションキャプチャーデータのアニメーション演出
「ユニティちゃんを踊らせよう!」モーションキャプチャーデータのアニメーション演出「ユニティちゃんを踊らせよう!」モーションキャプチャーデータのアニメーション演出
「ユニティちゃんを踊らせよう!」モーションキャプチャーデータのアニメーション演出
小林 信行
 
Introduction of openGL
Introduction  of openGLIntroduction  of openGL
Introduction of openGL
Gary Yeh
 
C++でCプリプロセッサを作ったり速くしたりしたお話
C++でCプリプロセッサを作ったり速くしたりしたお話C++でCプリプロセッサを作ったり速くしたりしたお話
C++でCプリプロセッサを作ったり速くしたりしたお話
Kinuko Yasuda
 
MVVM with SwiftUI and Combine
MVVM with SwiftUI and CombineMVVM with SwiftUI and Combine
MVVM with SwiftUI and Combine
Tai Lun Tseng
 
IPv6 を始めてみた
IPv6 を始めてみたIPv6 を始めてみた
IPv6 を始めてみた
miki koganei
 
インタフェース完全に理解した
インタフェース完全に理解したインタフェース完全に理解した
インタフェース完全に理解した
torisoup
 
Building the Game Server both API and Realtime via c#
Building the Game Server both API and Realtime via c#Building the Game Server both API and Realtime via c#
Building the Game Server both API and Realtime via c#
Yoshifumi Kawai
 
Vue入門
Vue入門Vue入門
Vue入門
Takeo Noda
 
Real-world game development with Ebitengine - How to make the best-selling G...
Real-world game development with Ebitengine -  How to make the best-selling G...Real-world game development with Ebitengine -  How to make the best-selling G...
Real-world game development with Ebitengine - How to make the best-selling G...
Daigo Sato
 
FlutterをRenderObjectまで理解する
FlutterをRenderObjectまで理解するFlutterをRenderObjectまで理解する
FlutterをRenderObjectまで理解する
KeisukeKiriyama
 
React-konvaで絵を描いてみる話
React-konvaで絵を描いてみる話React-konvaで絵を描いてみる話
React-konvaで絵を描いてみる話
iPride Co., Ltd.
 
Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現
Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現
Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現
Yoshifumi Kawai
 
benjamin kenwright webgpu api lecture 1.pptx
benjamin kenwright webgpu api lecture 1.pptxbenjamin kenwright webgpu api lecture 1.pptx
benjamin kenwright webgpu api lecture 1.pptx
Authorised
 
UniRxことはじめ
UniRxことはじめUniRxことはじめ
UniRxことはじめ
Shoichi Yasui
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game Framework
Nick Pruehs
 
Unityでオンラインゲーム作った話
Unityでオンラインゲーム作った話Unityでオンラインゲーム作った話
Unityでオンラインゲーム作った話
torisoup
 

What's hot (20)

"The 5 Personas of Product Management (and How to Hire for Them)" by Jason Shen
"The 5 Personas of Product Management (and How to Hire for Them)" by Jason Shen"The 5 Personas of Product Management (and How to Hire for Them)" by Jason Shen
"The 5 Personas of Product Management (and How to Hire for Them)" by Jason Shen
 
Low-level Shader Optimization for Next-Gen and DX11 by Emil Persson
Low-level Shader Optimization for Next-Gen and DX11 by Emil PerssonLow-level Shader Optimization for Next-Gen and DX11 by Emil Persson
Low-level Shader Optimization for Next-Gen and DX11 by Emil Persson
 
Visible surface detection in computer graphic
Visible surface detection in computer graphicVisible surface detection in computer graphic
Visible surface detection in computer graphic
 
WkWebViewのキャッシュについて調べた
WkWebViewのキャッシュについて調べたWkWebViewのキャッシュについて調べた
WkWebViewのキャッシュについて調べた
 
「ユニティちゃんを踊らせよう!」モーションキャプチャーデータのアニメーション演出
「ユニティちゃんを踊らせよう!」モーションキャプチャーデータのアニメーション演出「ユニティちゃんを踊らせよう!」モーションキャプチャーデータのアニメーション演出
「ユニティちゃんを踊らせよう!」モーションキャプチャーデータのアニメーション演出
 
Introduction of openGL
Introduction  of openGLIntroduction  of openGL
Introduction of openGL
 
C++でCプリプロセッサを作ったり速くしたりしたお話
C++でCプリプロセッサを作ったり速くしたりしたお話C++でCプリプロセッサを作ったり速くしたりしたお話
C++でCプリプロセッサを作ったり速くしたりしたお話
 
MVVM with SwiftUI and Combine
MVVM with SwiftUI and CombineMVVM with SwiftUI and Combine
MVVM with SwiftUI and Combine
 
IPv6 を始めてみた
IPv6 を始めてみたIPv6 を始めてみた
IPv6 を始めてみた
 
インタフェース完全に理解した
インタフェース完全に理解したインタフェース完全に理解した
インタフェース完全に理解した
 
Building the Game Server both API and Realtime via c#
Building the Game Server both API and Realtime via c#Building the Game Server both API and Realtime via c#
Building the Game Server both API and Realtime via c#
 
Vue入門
Vue入門Vue入門
Vue入門
 
Real-world game development with Ebitengine - How to make the best-selling G...
Real-world game development with Ebitengine -  How to make the best-selling G...Real-world game development with Ebitengine -  How to make the best-selling G...
Real-world game development with Ebitengine - How to make the best-selling G...
 
FlutterをRenderObjectまで理解する
FlutterをRenderObjectまで理解するFlutterをRenderObjectまで理解する
FlutterをRenderObjectまで理解する
 
React-konvaで絵を描いてみる話
React-konvaで絵を描いてみる話React-konvaで絵を描いてみる話
React-konvaで絵を描いてみる話
 
Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現
Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現
Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現
 
benjamin kenwright webgpu api lecture 1.pptx
benjamin kenwright webgpu api lecture 1.pptxbenjamin kenwright webgpu api lecture 1.pptx
benjamin kenwright webgpu api lecture 1.pptx
 
UniRxことはじめ
UniRxことはじめUniRxことはじめ
UniRxことはじめ
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game Framework
 
Unityでオンラインゲーム作った話
Unityでオンラインゲーム作った話Unityでオンラインゲーム作った話
Unityでオンラインゲーム作った話
 

Viewers also liked

Drawing with Quartz on iOS
Drawing with Quartz on iOSDrawing with Quartz on iOS
Drawing with Quartz on iOS
Bob 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 Foundation
Bob McCune
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngine
Bob McCune
 
Master Video with AV Foundation
Master Video with AV FoundationMaster Video with AV Foundation
Master Video with AV Foundation
Bob McCune
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java Developers
Bob McCune
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View Controllers
Bob McCune
 
Core Animation
Core AnimationCore Animation
Core Animation
Bob McCune
 
Xinghuo beam angle adjustable led track light
Xinghuo beam angle adjustable led track lightXinghuo beam angle adjustable led track light
Xinghuo beam angle adjustable led track light
John Zuo TUV GS LED light john.zuo88@gmail.com
 
Introduction to AV Foundation
Introduction to AV FoundationIntroduction to AV Foundation
Introduction to AV Foundation
Chris Adamson
 
Swift 3 Programming for iOS : subscript init
Swift 3 Programming for iOS : subscript initSwift 3 Programming for iOS : subscript init
Swift 3 Programming for iOS : subscript init
Kwang Woo NAM
 
[공간정보시스템 개론] L04 항공사진의 이해
[공간정보시스템 개론] L04 항공사진의 이해[공간정보시스템 개론] L04 항공사진의 이해
[공간정보시스템 개론] L04 항공사진의 이해
Kwang Woo NAM
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
John Wilker
 
Mastering Media with AV Foundation
Mastering Media with AV FoundationMastering Media with AV Foundation
Mastering Media with AV Foundation
Chris Adamson
 
CARBON RECOVERY FROM SPONGE IRON PLANT DUST
CARBON RECOVERY FROM SPONGE IRON PLANT DUSTCARBON RECOVERY FROM SPONGE IRON PLANT DUST
CARBON RECOVERY FROM SPONGE IRON PLANT DUST
RADE INITIATIVE
 
Animation in iOS
Animation in iOSAnimation in iOS
Animation in iOS
Alexis Goldstein
 
CRYOGENIC ROCKET ENGINE
CRYOGENIC ROCKET ENGINECRYOGENIC ROCKET ENGINE
CRYOGENIC ROCKET ENGINE
TechWorksLab Private Limited
 
20 iOS developer interview questions
20 iOS developer interview questions20 iOS developer interview questions
20 iOS developer interview questions
Arc & Codementor
 
iOS Developer Interview Questions
iOS Developer Interview QuestionsiOS Developer Interview Questions
iOS Developer Interview Questions
Clark Davidson
 
Applications of piezo-electricity
Applications of piezo-electricityApplications of piezo-electricity
Applications of piezo-electricity
Sakti Prasanna Muduli
 
The Basics Of Car Maintenance
The Basics Of  Car MaintenanceThe Basics Of  Car Maintenance
The Basics Of Car Maintenance
Dreamcars Auto Repair
 

Viewers also liked (20)

Drawing with Quartz on iOS
Drawing with Quartz on iOSDrawing with Quartz on iOS
Drawing with Quartz on iOS
 
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
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngine
 
Master Video with AV Foundation
Master Video with AV FoundationMaster Video with AV Foundation
Master Video with AV Foundation
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java Developers
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View Controllers
 
Core Animation
Core AnimationCore Animation
Core Animation
 
Xinghuo beam angle adjustable led track light
Xinghuo beam angle adjustable led track lightXinghuo beam angle adjustable led track light
Xinghuo beam angle adjustable led track light
 
Introduction to AV Foundation
Introduction to AV FoundationIntroduction to AV Foundation
Introduction to AV Foundation
 
Swift 3 Programming for iOS : subscript init
Swift 3 Programming for iOS : subscript initSwift 3 Programming for iOS : subscript init
Swift 3 Programming for iOS : subscript init
 
[공간정보시스템 개론] L04 항공사진의 이해
[공간정보시스템 개론] L04 항공사진의 이해[공간정보시스템 개론] L04 항공사진의 이해
[공간정보시스템 개론] L04 항공사진의 이해
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
 
Mastering Media with AV Foundation
Mastering Media with AV FoundationMastering Media with AV Foundation
Mastering Media with AV Foundation
 
CARBON RECOVERY FROM SPONGE IRON PLANT DUST
CARBON RECOVERY FROM SPONGE IRON PLANT DUSTCARBON RECOVERY FROM SPONGE IRON PLANT DUST
CARBON RECOVERY FROM SPONGE IRON PLANT DUST
 
Animation in iOS
Animation in iOSAnimation in iOS
Animation in iOS
 
CRYOGENIC ROCKET ENGINE
CRYOGENIC ROCKET ENGINECRYOGENIC ROCKET ENGINE
CRYOGENIC ROCKET ENGINE
 
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
 
Applications of piezo-electricity
Applications of piezo-electricityApplications of piezo-electricity
Applications of piezo-electricity
 
The Basics Of Car Maintenance
The Basics Of  Car MaintenanceThe Basics Of  Car Maintenance
The Basics Of Car Maintenance
 

Similar to Quartz 2D with Swift 3

Rotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billyRotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billynimbleltd
 
Point cloud mesh-investigation_report-lihang
Point cloud mesh-investigation_report-lihangPoint cloud mesh-investigation_report-lihang
Point cloud mesh-investigation_report-lihang
Lihang Li
 
Copy Your Favourite Nokia App with Qt
Copy Your Favourite Nokia App with QtCopy Your Favourite Nokia App with Qt
Copy Your Favourite Nokia App with Qt
account inactive
 
INAC Online Hazards Database App
INAC Online Hazards Database AppINAC Online Hazards Database App
INAC Online Hazards Database App
Gerry James
 
Chapter-3.pdf
Chapter-3.pdfChapter-3.pdf
Getting Started with CoreGraphics
Getting Started with CoreGraphicsGetting Started with CoreGraphics
Getting Started with CoreGraphics
Xamarin
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
Nissan Tsafrir
 
Text Layout With Core Text
Text Layout With Core TextText Layout With Core Text
Text Layout With Core TextDavid Ding
 
HTML5 Canvas
HTML5 CanvasHTML5 Canvas
HTML5 Canvas
Robyn Overstreet
 
An Introduction to NV_path_rendering
An Introduction to NV_path_renderingAn Introduction to NV_path_rendering
An Introduction to NV_path_rendering
Mark Kilgard
 
Webrender 1.0
Webrender 1.0Webrender 1.0
Webrender 1.0
Daosheng Mu
 
Migrating Objective-C to Swift
Migrating Objective-C to SwiftMigrating Objective-C to Swift
Migrating Objective-C to Swift
Elmar Kretzer
 
Introduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene GraphIntroduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene Graph
ICS
 
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
StanfordComputationalImaging
 
Matlab robotics toolbox
Matlab robotics toolboxMatlab robotics toolbox
Matlab robotics toolbox
Rajesh Raveendran
 
Android RenderScript on LLVM
Android RenderScript on LLVMAndroid RenderScript on LLVM
Android RenderScript on LLVM
John Lee
 
Animating an svg icon
Animating an svg iconAnimating an svg icon
Animating an svg icon
deepbidis
 
Hardware Accelerated 2D Rendering for Android
Hardware Accelerated 2D Rendering for AndroidHardware Accelerated 2D Rendering for Android
Hardware Accelerated 2D Rendering for Android
National Cheng Kung University
 
Open Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 TutorialOpen Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 Tutorial
antiw
 

Similar to Quartz 2D with Swift 3 (20)

Rotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billyRotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billy
 
Point cloud mesh-investigation_report-lihang
Point cloud mesh-investigation_report-lihangPoint cloud mesh-investigation_report-lihang
Point cloud mesh-investigation_report-lihang
 
Copy Your Favourite Nokia App with Qt
Copy Your Favourite Nokia App with QtCopy Your Favourite Nokia App with Qt
Copy Your Favourite Nokia App with Qt
 
INAC Online Hazards Database App
INAC Online Hazards Database AppINAC Online Hazards Database App
INAC Online Hazards Database App
 
Chapter-3.pdf
Chapter-3.pdfChapter-3.pdf
Chapter-3.pdf
 
Getting Started with CoreGraphics
Getting Started with CoreGraphicsGetting Started with CoreGraphics
Getting Started with CoreGraphics
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
 
Text Layout With Core Text
Text Layout With Core TextText Layout With Core Text
Text Layout With Core Text
 
HTML5 Canvas
HTML5 CanvasHTML5 Canvas
HTML5 Canvas
 
An Introduction to NV_path_rendering
An Introduction to NV_path_renderingAn Introduction to NV_path_rendering
An Introduction to NV_path_rendering
 
Webrender 1.0
Webrender 1.0Webrender 1.0
Webrender 1.0
 
Migrating Objective-C to Swift
Migrating Objective-C to SwiftMigrating Objective-C to Swift
Migrating Objective-C to Swift
 
Introduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene GraphIntroduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene Graph
 
Cad notes
Cad notesCad notes
Cad notes
 
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
 
Matlab robotics toolbox
Matlab robotics toolboxMatlab robotics toolbox
Matlab robotics toolbox
 
Android RenderScript on LLVM
Android RenderScript on LLVMAndroid RenderScript on LLVM
Android RenderScript on LLVM
 
Animating an svg icon
Animating an svg iconAnimating an svg icon
Animating an svg icon
 
Hardware Accelerated 2D Rendering for Android
Hardware Accelerated 2D Rendering for AndroidHardware Accelerated 2D Rendering for Android
Hardware Accelerated 2D Rendering for Android
 
Open Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 TutorialOpen Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 Tutorial
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 

Quartz 2D with Swift 3

  • 2. -Overview of the Quartz framework - What is it? - When do you need it? -Core capabilities of framework: - Contexts and Paths - Drawing lines, curves, and images - Applying transformations -Recipes and Examples Agenda What will I learn?
  • 4. -Apple’s 2D drawing framework based on the PDF imaging model -Graphics API to produce lines, curves, transforms, gradients, etc. -Uses painters model for drawing operations What is Quartz 2D? Wasn’t this supposed to be about Core Graphics? Drawing Order Result
  • 5. -Prefer to build your UI using images - Better performance and caching - Easier to create and maintain - Keeps your graphics designers employed -It’s best to design your UI using images… When do I need it? Isn’t this what graphics designers are for? ...until you can’t
  • 6.
  • 7.
  • 8.
  • 10. Objective-C CGContext *context = [[CGContext alloc] init]; [context moveToPoint:CGPointMake(12.0f, 12.0f)]; [context addLineToPoint:CGPointMake(24.0f, 24.0f)]; [context fill]; Understanding the Syntax Dude, where’s my objects?
  • 11. Understanding the Syntax Dude, where’s my objects? Objective-C CGContext *context = [[CGContext alloc] init]; [context moveToPoint:CGPointMake(12.0f, 12.0f)]; [context addLineToPoint:CGPointMake(24.0f, 24.0f)]; [context fill]; Standard C CGContextRef context = UIGraphicsGetCurrentContext(); CGContextMoveToPoint(context, 12.0f, 12.0f); CGContextAddLineToPoint(context, 24.0f, 24.0f); CGContextFillPath(context); Quartz not an Objective-C API
  • 12. Understanding the Syntax Dude, where’s my objects? Standard C CGContextRef context = UIGraphicsGetCurrentContext(); CGContextMoveToPoint(context, 12.0f, 12.0f); CGContextAddLineToPoint(context, 24.0f, 24.0f); CGContextFillPath(context); Swift 2 let context = UIGraphicsGetCurrentContext()! CGContextMoveToPoint(context, 12.0, 12.0) CGContextAddLineToPoint(context, 24.0, 24.0) CGContextFillPath(context)
  • 13. Understanding the Syntax Dude, where’s my objects? Swift 3 let context = UIGraphicsGetCurrentContext()! context.move(to: CGPoint(x: 12.0, y: 12.0)) context.addLine(to: CGPoint(x: 24.0, y: 24.0)) context.fillPath() Swift 2 let context = UIGraphicsGetCurrentContext()! CGContextMoveToPoint(context, 12.0, 12.0) CGContextAddLineToPoint(context, 24.0, 24.0) CGContextFillPath(context) Session 403: Swift API Design Guidelines (WWDC 2016)
  • 15. -Graphics context provides the drawing area -Manages core drawing states: - Colors, line widths, transforms, etc. - It’s a state machine -Key Quartz Contexts: - CGContext - CGBitmapContext - CGPDFContext Quartz Graphics Contexts The Canvas
  • 16. -Current Transformation Matrix (CTM) defines the coordinate system -Coordinate system varies on macOS and iOS/tvOS Quartz Coordinate System Drawing Orientation 0, 0 y x Positive 0, 0 y x Positive macOS iOS and tvOS
  • 17. -Drawing is defined in terms of points -Points are abstract, infinitely thin -Points live in User Space CGContext Drawing Quartz Points p0 p1
  • 18. Points are Device-Independent Think in points not pixels H: 70 L:46 Sunny Cupertino 66 p0 p1
  • 19. -CGContext is the default drawing context - Created by UIKit and AppKit -Get a reference to it: CGContext Drawing CGContext let context = UIGraphicsGetCurrentContext() iOS and tvOS let context = NSGraphicsContext.current()?.graphicsPort macOS
  • 23. Getting Started Where do I draw? class HelloQuartzViewController: UIViewController { func drawBackground(recognizer: UIGestureRecognizer) { } } let context = UIGraphicsGetCurrentContext() context?.setFillColor(randomColor()) context?.fill(view.bounds)
  • 24. Getting Started Where do I draw? class HelloQuartzView: UIView { override func draw(_ rect: CGRect) { } } class HelloQuartzViewController: UIViewController { func drawBackground(recognizer: UIGestureRecognizer) { } } let context = UIGraphicsGetCurrentContext() context?.setFillColor(randomColor()) context?.fill(view.bounds)
  • 25. Getting Started Where do I draw? class HelloQuartzView: UIView { override func draw(_ rect: CGRect) { } } class HelloQuartzViewController: UIViewController { func drawBackground(recognizer: UIGestureRecognizer) { } } let context = UIGraphicsGetCurrentContext() context?.setFillColor(randomColor()) context?.fill(view.bounds) // Trigger call to HelloQuartzView's draw(:) method helloView.setNeedsDisplay()
  • 27. CGContext Drawing Defining Paths (0, 0) (100, 100) let rect = CGRect(x: 0, y: 0, width: 100, height: 100) context.addRect(rect)
  • 28. CGContext Drawing Defining Paths (0, 0) (100, 100) let rect = CGRect(x: 0, y: 0, width: 100, height: 100) context.addEllipse(in: rect)
  • 29. CGContext Drawing Defining Paths (0, 0) (100, 100) context.setStrokeColor(white) context.drawPath(using: .stroke)
  • 30. CGContext Drawing Defining Paths (0, 0) (100, 100) context.setFillColor(yellow) context.drawPath(using: .fill)
  • 31. CGContext Drawing Defining Paths (0, 0) (100, 100) context.drawPath(using: .fillStroke)
  • 32. -Colors must be defined on the context before drawing -Fill Colors - setFillColor(color: CGColor) - setFillColor(gray: CGFloat, alpha: CGFloat) - setFillColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -Stroke Colors - setStrokeColor(color: CGColor) - setStrokeColor(gray: CGFloat, alpha: CGFloat) - setStrokeColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) Defining Colors CGColor
  • 33. - CGColor is the native Quartz color type - UIColor is the native UIKit color type -Use UIColor in almost all cases - Easier to create - Named color initializers - Easy to convert to and from CGColor Defining Colors CGColor vs UIColor // Convert to Quartz Type let cgColor = UIColor.red.cgColor context.setFillColor(cgColor) // Convert to UIKit Type let uiColor = UIColor(cgColor: cgColor)
  • 34. -Lines are the most essential primitive -Lines are always defined by their endpoints -Basic Recipe: 1. Begin a new path 2. Move to initial starting point 3. Add lines defining shape 4. Close the path (optional) 5. Draw Path Drawing Lines Defining Paths
  • 40. CGContext Drawing Constructing Paths let whiteColor = UIColor.white context.setFillColor(whiteColor.cgColor)
  • 43. -Arcs define circle segments -Arcs are defined with the following: - Center x, y coordinates - Radius - Start and stop angles (in radians) - Direction (clockwise or counter-clockwise) -Created using: - addArc(center:radius:startAngle:endAngle:clockwise:) - addArc(tangent1End:tangent2End:radius:) Drawing Arcs Constructing Paths
  • 44. -Arc functions are not aware of flipped coordinate system - Need to think upside down (or) - Transform coordinate system before using - UIBezierPath wraps Quartz GGPath functionality - Access to underlying path with CGPath property -Generally easier to use UIBezierPath on iOS and tvOS - * In Swift 3, direct Quartz usages is very similar UIBezierPath More iOS/tvOS-friendly solution
  • 45. Drawing Arcs Defining Paths let path = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle: 0, endAngle: degreesToRadians(270.0), clockwise: false) path.addLine(to: centerPoint) context.addPath(path.cgPath)
  • 46. Quadratic Bézier Curves Constructing Paths p0 context.beginPath() context.move(to: p0)
  • 47. Quadratic Bézier Curves Constructing Paths p0 p1 cp context.addQuadCurve(to: p1, control: controlPoint)
  • 48. Quadratic Bézier Curves Constructing Paths p0 p1 cp context.setLineWidth(2.0) context.setStrokeColor(UIColor.green.cgColor) context.strokePath()
  • 49. Cubic Bézier Curves Constructing Paths p0 context.beginPath(); context.move(to: p0)
  • 50. Cubic Bézier Curves Constructing Paths p0 cp1 p1 cp2 context.addCurve(to: p1, control1: cp1, control2: cp2)
  • 51. Cubic Bézier Curves Constructing Paths p0 cp1 cp2 p1 -cp1 -cp2 let tx = CGAffineTransform(scaleX: -1, y: 1) context.addCurve(to: p0, control1: cp2.applying(tx), control2: cp1.applying(tx))
  • 52. Cubic Bézier Curves Constructing Paths p0 cp1 cp2 p1 cp1 -cp2 context.closePath() context.setFillColor(UIColor.red.cgColor) context.fillPath()
  • 53. -Quartz uses fill rules to determine what’s inside and outside of a path. -Uses one of the following: - Non-zero Winding Rule (Default) - Even Odd Rule Fill Rules To fill, or not to fill
  • 55. -Affine transformations are essential to all graphics programming regardless of platform -Allow you to manipulate the coordinate system to translate, scale, skew, and rotate -Transform preserves collinearity of lines Affine Transformations Transforming the Coordinate System X
  • 56. -CTM can be modified with the following: - translateBy(x:y:) - scaleBy(x:y:) - rotate(by:) Current Transformation Matrix Modifying the CTM
  • 57. Translate Moving the Origin Point (0, 0) (100, 100)
  • 58. Translate Moving the Origin Point (0, 0) (0, 0) context.translateBy(x: 100, y: 100)
  • 59. Scale Scaling the Unit Size (0, 0) (200, 200)
  • 60. Scale Scaling the Unit Size (0, 0) (200, 200) context.scaleBy(x: 2.0, y: 2.0)
  • 63. -A gradient is a fill that varies from one color to another -Quartz supports two different gradient types - Linear varies between two endpoints - Radial varies between two radial endpoints Gradients Drawing Gradients Linear Radial
  • 64. -Gradients can be created using either: - init(colorsSpace:colors:locations:) - init(colorSpace:colorComponents:locations:) -Both functions require the following: - CGColorSpace - Colors (components or array of CGColor) - Array of CGFloat values defining gradient color stops Creating a CGGradient CGGradient
  • 65. CGGradientRef Building the gradient code let startColor = UIColor.red let endColor = UIColor.orange let colors = [startColor.cgColor, endColor.cgColor] as CFArray let locations: [CGFloat] = [0, 1] let colorSpace = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations)! let startPoint = CGPoint(x: rect.midX, y: rect.minY) let endPoint = CGPoint(x: rect.midX, y: rect.maxY) let opts = CGGradientDrawingOptions() context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: opts)
  • 68. -Quartz has broad support for images -Represented as CGImage -Can be drawn using: - draw(image:rect:) - draw(image:rect:byTiling) - CGBitmapContext allows for dynamically building image data Working with Images CGImage
  • 69. -Don’t draw in Quartz. Use UIImageView. -Choose UIImage over CGImage - Easier to load and cache image content - Provides methods for drawing - Is aware flipped coordinate system - UIImage provides a CGImage property -Use CGImage for more advanced cases - Cropping, scaling, masking - Dynamic image creation CGImage vs UIImage Which should I use?
  • 70. Using Image Masks Hiding behind a mask
  • 71. Using Image Masks Hiding behind a mask // Mask image created by toMask() extension guard let maskImage = UIImage(named: “round_mask")?.cgImage?.toMask() else { return } guard let jeffersonImage = UIImage(named: "jefferson")?.cgImage else { return } if let masked = jeffersonImage.masking(maskImage) { // Draw shadow to offset from background let shadowOffset = CGSize(width: 1, height: 1) let shadowColor = UIColor.darkGray.cgColor context.setShadow(offset: shadowOffset, blur: 12, color: shadowColor) let maskedImage = UIImage(cgImage: masked) maskedImage.draw(in: drawingRect(for: maskedImage)) }
  • 72. Cropping Images cropping(to:) let albumImage = UIImage(named: "vh1")! let cropRect = CGRect(x: 20, y: 20, width: 200, height: 200) if let cgImage = albumImage.cgImage?.cropping(to: cropRect) { // Create new UIImage and use as needed let eddieImage = UIImage(cgImage: cgImage) }
  • 73. -Quartz is a powerful drawing engine for Apple platforms -Essential skill to master to build beautiful apps -Quartz + Swift 3 = Awesome Summary
  • 74. Resources Quartz 2D Programming Guide http://developer.apple.com/ Programming with Quartz David Gelphman Bunny Laden