SlideShare une entreprise Scribd logo
1  sur  74
@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

Contenu connexe

Tendances

GraalVMのJavaネイティブビルド機能でどの程度起動が速くなるのか?~サーバレス基盤上での評価~ / How fast does GraalVM's...
GraalVMのJavaネイティブビルド機能でどの程度起動が速くなるのか?~サーバレス基盤上での評価~ / How fast does GraalVM's...GraalVMのJavaネイティブビルド機能でどの程度起動が速くなるのか?~サーバレス基盤上での評価~ / How fast does GraalVM's...
GraalVMのJavaネイティブビルド機能でどの程度起動が速くなるのか?~サーバレス基盤上での評価~ / How fast does GraalVM's...Shinji Takao
 
I/O仮想化最前線〜ネットワークI/Oを中心に〜
I/O仮想化最前線〜ネットワークI/Oを中心に〜I/O仮想化最前線〜ネットワークI/Oを中心に〜
I/O仮想化最前線〜ネットワークI/Oを中心に〜Ryousei Takano
 
공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반
공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반
공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반MinPa Lee
 
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례BJ Jang
 
Linux on RISC-V with Open Source Hardware (Open Source Summit Japan 2020)
Linux on RISC-V with Open Source Hardware (Open Source Summit Japan 2020)Linux on RISC-V with Open Source Hardware (Open Source Summit Japan 2020)
Linux on RISC-V with Open Source Hardware (Open Source Summit Japan 2020)Drew Fustini
 
State of OpenGXT: 오픈소스 공간분석엔진
State of OpenGXT: 오픈소스 공간분석엔진State of OpenGXT: 오픈소스 공간분석엔진
State of OpenGXT: 오픈소스 공간분석엔진MinPa Lee
 
こんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツールこんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツールdcubeio
 
FlutterでGraphQLを扱う
FlutterでGraphQLを扱うFlutterでGraphQLを扱う
FlutterでGraphQLを扱うIgaHironobu
 
JavaScript GIS ライブラリ turf.js 入門
JavaScript GIS ライブラリ turf.js 入門JavaScript GIS ライブラリ turf.js 入門
JavaScript GIS ライブラリ turf.js 入門Takahiro Kamada
 
みんな大好きJava gc入門 【前編】
みんな大好きJava gc入門 【前編】みんな大好きJava gc入門 【前編】
みんな大好きJava gc入門 【前編】kouzirou tenkubashi
 
サーバーサイド Kotlin のテストフレームワーク事情
サーバーサイド Kotlin のテストフレームワーク事情サーバーサイド Kotlin のテストフレームワーク事情
サーバーサイド Kotlin のテストフレームワーク事情Shinya Mochida
 
오픈소스 GIS의 이해와 활용(육군사관학교 특강)
오픈소스 GIS의 이해와 활용(육군사관학교 특강)오픈소스 GIS의 이해와 활용(육군사관학교 특강)
오픈소스 GIS의 이해와 활용(육군사관학교 특강)SANGHEE SHIN
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsScott Gardner
 
【BS3】Visual Studio 2022 と .NET 6 での Windows アプリ開発技術の紹介
【BS3】Visual Studio 2022 と .NET 6 での Windows アプリ開発技術の紹介 【BS3】Visual Studio 2022 と .NET 6 での Windows アプリ開発技術の紹介
【BS3】Visual Studio 2022 と .NET 6 での Windows アプリ開発技術の紹介 日本マイクロソフト株式会社
 
Zynq + Vivado HLS入門
Zynq + Vivado HLS入門Zynq + Vivado HLS入門
Zynq + Vivado HLS入門narusugimoto
 

Tendances (20)

GraalVMのJavaネイティブビルド機能でどの程度起動が速くなるのか?~サーバレス基盤上での評価~ / How fast does GraalVM's...
GraalVMのJavaネイティブビルド機能でどの程度起動が速くなるのか?~サーバレス基盤上での評価~ / How fast does GraalVM's...GraalVMのJavaネイティブビルド機能でどの程度起動が速くなるのか?~サーバレス基盤上での評価~ / How fast does GraalVM's...
GraalVMのJavaネイティブビルド機能でどの程度起動が速くなるのか?~サーバレス基盤上での評価~ / How fast does GraalVM's...
 
I/O仮想化最前線〜ネットワークI/Oを中心に〜
I/O仮想化最前線〜ネットワークI/Oを中心に〜I/O仮想化最前線〜ネットワークI/Oを中心に〜
I/O仮想化最前線〜ネットワークI/Oを中心に〜
 
공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반
공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반
공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반
 
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
 
Linux on RISC-V with Open Source Hardware (Open Source Summit Japan 2020)
Linux on RISC-V with Open Source Hardware (Open Source Summit Japan 2020)Linux on RISC-V with Open Source Hardware (Open Source Summit Japan 2020)
Linux on RISC-V with Open Source Hardware (Open Source Summit Japan 2020)
 
State of OpenGXT: 오픈소스 공간분석엔진
State of OpenGXT: 오픈소스 공간분석엔진State of OpenGXT: 오픈소스 공간분석엔진
State of OpenGXT: 오픈소스 공간분석엔진
 
Git由超淺入超深
Git由超淺入超深Git由超淺入超深
Git由超淺入超深
 
こんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツールこんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツール
 
FlutterでGraphQLを扱う
FlutterでGraphQLを扱うFlutterでGraphQLを扱う
FlutterでGraphQLを扱う
 
JavaScript GIS ライブラリ turf.js 入門
JavaScript GIS ライブラリ turf.js 入門JavaScript GIS ライブラリ turf.js 入門
JavaScript GIS ライブラリ turf.js 入門
 
みんな大好きJava gc入門 【前編】
みんな大好きJava gc入門 【前編】みんな大好きJava gc入門 【前編】
みんな大好きJava gc入門 【前編】
 
サーバーサイド Kotlin のテストフレームワーク事情
サーバーサイド Kotlin のテストフレームワーク事情サーバーサイド Kotlin のテストフレームワーク事情
サーバーサイド Kotlin のテストフレームワーク事情
 
오픈소스 GIS의 이해와 활용(육군사관학교 특강)
오픈소스 GIS의 이해와 활용(육군사관학교 특강)오픈소스 GIS의 이해와 활용(육군사관학교 특강)
오픈소스 GIS의 이해와 활용(육군사관학교 특강)
 
Git Tutorial 教學
Git Tutorial 教學Git Tutorial 教學
Git Tutorial 教學
 
Golang workshop
Golang workshopGolang workshop
Golang workshop
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the Things
 
【BS3】Visual Studio 2022 と .NET 6 での Windows アプリ開発技術の紹介
【BS3】Visual Studio 2022 と .NET 6 での Windows アプリ開発技術の紹介 【BS3】Visual Studio 2022 と .NET 6 での Windows アプリ開発技術の紹介
【BS3】Visual Studio 2022 と .NET 6 での Windows アプリ開発技術の紹介
 
Spring Framework勉強会
Spring  Framework勉強会Spring  Framework勉強会
Spring Framework勉強会
 
Zynq + Vivado HLS入門
Zynq + Vivado HLS入門Zynq + Vivado HLS入門
Zynq + Vivado HLS入門
 
webworkers
webworkerswebworkers
webworkers
 

En vedette

Drawing with Quartz on iOS
Drawing with Quartz on iOSDrawing with Quartz on iOS
Drawing with Quartz on iOSBob McCune
 
Composing and Editing Media with AV Foundation
Composing and Editing Media with AV FoundationComposing and Editing Media with AV Foundation
Composing and Editing Media with AV FoundationBob McCune
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBob McCune
 
Master Video with AV Foundation
Master Video with AV FoundationMaster Video with AV Foundation
Master Video with AV FoundationBob McCune
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java DevelopersBob McCune
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View ControllersBob McCune
 
Core Animation
Core AnimationCore Animation
Core AnimationBob McCune
 
Introduction to AV Foundation
Introduction to AV FoundationIntroduction to AV Foundation
Introduction to AV FoundationChris 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 initKwang Woo NAM
 
[공간정보시스템 개론] L04 항공사진의 이해
[공간정보시스템 개론] L04 항공사진의 이해[공간정보시스템 개론] L04 항공사진의 이해
[공간정보시스템 개론] L04 항공사진의 이해Kwang Woo NAM
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core AnimationJohn Wilker
 
Mastering Media with AV Foundation
Mastering Media with AV FoundationMastering Media with AV Foundation
Mastering Media with AV FoundationChris 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 DUSTRADE INITIATIVE
 
20 iOS developer interview questions
20 iOS developer interview questions20 iOS developer interview questions
20 iOS developer interview questionsArc & Codementor
 
iOS Developer Interview Questions
iOS Developer Interview QuestionsiOS Developer Interview Questions
iOS Developer Interview QuestionsClark Davidson
 

En vedette (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
 

Similaire à Bob McCune's Quartz 2D with Swift 3 Overview

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-lihangLihang 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 Qtaccount inactive
 
INAC Online Hazards Database App
INAC Online Hazards Database AppINAC Online Hazards Database App
INAC Online Hazards Database AppGerry James
 
Getting Started with CoreGraphics
Getting Started with CoreGraphicsGetting Started with CoreGraphics
Getting Started with CoreGraphicsXamarin
 
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-CNissan Tsafrir
 
Text Layout With Core Text
Text Layout With Core TextText Layout With Core Text
Text Layout With Core TextDavid Ding
 
An Introduction to NV_path_rendering
An Introduction to NV_path_renderingAn Introduction to NV_path_rendering
An Introduction to NV_path_renderingMark Kilgard
 
Migrating Objective-C to Swift
Migrating Objective-C to SwiftMigrating Objective-C to Swift
Migrating Objective-C to SwiftElmar 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 GraphICS
 
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 2StanfordComputationalImaging
 
Android RenderScript on LLVM
Android RenderScript on LLVMAndroid RenderScript on LLVM
Android RenderScript on LLVMJohn Lee
 
Animating an svg icon
Animating an svg iconAnimating an svg icon
Animating an svg icondeepbidis
 
Open Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 TutorialOpen Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 Tutorialantiw
 

Similaire à Bob McCune's Quartz 2D with Swift 3 Overview (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
 

Dernier

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 

Dernier (20)

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 

Bob McCune's Quartz 2D with Swift 3 Overview

  • 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