SlideShare a Scribd company logo
1 of 74
Download to read offline
Drawing with
Quartz on iOS


       http://bobmccune.com



       http://tapharmonic.com
Agenda
• Overview of the Quartz framework
 • What is it?
 • When do you need it?
• Key framework functionality:
 • Contexts and Paths
 • Drawing lines, curves, and images
 • Applying transformations
• Recipes and Examples
What is Quartz?
What is Quartz?
Wasn’t this talk supposed to be about Core Graphics?

 • 2D drawing engine for Mac and iOS based
   on the PDF imaging model
 • Graphics API to produce lines, curves,
   transformations, gradients, etc.
 • Uses painters model for drawing operations




      Drawing Order                            Result
When do I need it?
Isn’t this what graphic designers are for?

 • Always build your UI from images
    • Better performance and caching
    • Easier to create and maintain
    • Keeps your graphic designers employed
 • Always, always, always use images...

                          ...until you can’t
Getting Started
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];
Understanding the Syntax
Dude, where’s my objects?

Objective-C
CGContext *context = [[CGContext alloc] init];
  Quartz is not an Objective-C API
[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 is Consistent
Naming Conventions
Functions always use the following convention:

   <Type><Action>(<Object>, <Arguments);

CGContextMoveToPoint(context, 12.0f, 12.0f);

CGPathAddLineToPoint(path, NULL, 22.0f, 100.0f);

CGPDFContextClose(context);
Graphics Contexts
Quartz Graphics Contexts
The Canvas

 • 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 Coordinate System
Drawing Orientation

 • Current Transformation Matrix (CTM)
   defines the coordinate system
 • Coordinate system varies on Mac and iOS
     y                Positive   0, 0
                                                       x




                           x
  0, 0                                  y         Positive
         Mac OS X                           iOS
CGContext Drawing
Quartz Points


 • Drawing is        p0
   defined in terms
   of points
 • Points are
   abstract,
   infinitely thin
 • Points live in    p1
   User Space
Points are Device-Independent
Think in points not pixels


               p0




               p1
CGContext Drawing
CGContextRef

 • CGContextRef is the drawing context
   • Created by UIKit and AppKit
 • Get a pointer reference to it:
  iOS
  CGContextRef context = UIGraphicsGetCurrentContext();

  Mac
  NSGraphicsContext *current =
     [NSGraphicsContext currentContext];
  CGContextRef context = (CGContextRef)[current graphicsPort];
Getting Started
Where do I draw?
Getting Started
Where do I draw?

@implementation HelloQuartzViewController

- (void)drawBackground:(UIGestureRecognizer *)recognizer {
	 CGContextRef context = UIGraphicsGetCurrentContext();
	 CGContextSetFillColorWithColor(context, THRandomColor());
	 CGContextFillRect(context, self.view.bounds);	
}

@end
Getting Started
Where do I draw?

@implementation HelloQuartzViewController

- (void)drawBackground:(UIGestureRecognizer *)recognizer {
   CGContextRef context = UIGraphicsGetCurrentContext();
   CGContextSetFillColorWithColor(context, THRandomColor());
   CGContextFillRect(context, self.view.bounds);	
}

@end




@implementation HelloQuartzView

- (void)drawRect:(CGRect)rect {




}

@end
Getting Started
Where do I draw?

@implementation HelloQuartzViewController

- (void)drawBackground:(UIGestureRecognizer *)recognizer {

    // Trigger call to HelloQuartzView's drawRect method (if needed)
    [self.helloView setNeedsDisplay];
}

@end




@implementation HelloQuartzView

- (void)drawRect:(CGRect)rect {
   CGContextRef context = UIGraphicsGetCurrentContext();
   CGContextSetFillColorWithColor(context, THRandomColor());
   CGContextFillRect(context, rect);	
}

@end
Basic Paths
CGContext Drawing
Defining Paths


                (0, 0)




                         (100, 100)




    CGRect rect = CGRectMake(0, 0, 100, 100);
    CGContextAddRect(context, rect);
CGContext Drawing
Defining Paths


                (0, 0)




                         (100, 100)




     CGRect rect = CGRectMake(0, 0, 100, 100);
     CGContextAddEllipseInRect(context, rect);
CGContext Drawing
Defining Paths


                (0, 0)




                         (100, 100)




 CGContextSetStrokeColorWithColor(context, white);
 CGContextDrawPath(context, kCGPathStroke);
CGContext Drawing
Defining Paths


                (0, 0)




                         (100, 100)




 CGContextSetFillColorWithColor(context, yellow);
 CGContextDrawPath(context, kCGPathFill);
CGContext Drawing
Defining Paths


                (0, 0)




                         (100, 100)




  CGContextDrawPath(context, kCGPathFillStroke);
Defining Colors
CGColorRef

 • Colors must be defined before drawing
 • Fill Colors
   •   CGContextSetFillColor
   •   CGContextSetFillColorWithColor
   •   CGContextSetRGBFillColor

 • Stroke Colors
   •   CGContextSetStrokeColor
   •   CGContextSetStrokeColorWithColor
   •   CGContextSetRGBStrokeColor
Defining Colors
CGColor vs UIColor

  • CGColor is the native Quartz color type
  • UIColor is the native UIKit color type
  • Use UIColor in almost all cases
    • Easier to create
      • Autoreleased convenience initializers
      • Named color initializers
    • Easy to convert to and from CGColor
CGColorRef redColor = [UIColor redColor].CGColor;
CGContextSetFillColorWithColor(context, redColor);
Drawing Lines
Defining Paths

 • 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.Optionally close the path
   5.Draw Path
CGContext Drawing
Defining Paths




      CGContextBeginPath(context);
      CGContextMoveToPoint(context, 0.0f, 0.0f);
CGContext Drawing
Defining Paths




  CGContextAddLineToPoint(context, 0.0f, 4.0f);
CGContext Drawing
Defining Paths




  CGContextAddLineToPoint(context, 4.0f, 4.0f);
CGContext Drawing
Defining Paths




  CGContextAddLineToPoint(context, 4.0f, 0.0f);
CGContext Drawing
Defining Paths




          CGContextClosePath(context);
CGContext Drawing
Defining Paths




 CGColorRef color = [UIColor whiteColor].CGColor;
 CGContextSetFillColorWithColor(context, color);
CGContext Drawing
Defining Paths




     CGContextDrawPath(context, kCGPathFill);
Advanced Paths
Drawing Arcs
Defining Paths

 • Arcs define circle segments
 • Arcs are defined with the following:
   • Center point x, y coordinates
   • Radius
   • Start and stop angles (in radians)
   • Direction (clockwise or counter-clockwise)
 • Created using:
   •   CGContextAddArc
   •   CGContextAddArcToPoint
UIBezierPath
More iOS-friendly solution

 • Arc functions are not aware of flipped
   coordinate system
    • Need to think upside down
    • Transform coordinate system before using
 • UIBezierPath provides a lightweight wrapper
   over Quartz path functionality
    • Access to underlying path with CGPath property
 • Easier to use UIBezierPath on iOS
Drawing Arcs
 Defining Paths




UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:centerPoint
                                                    radius:radius
                                                startAngle:0
                                                  endAngle:DEGREES(90)
                                                 clockwise:NO];
CGContextAddPath(context, path.CGPath);
Quadratic Bézier Curves
Single Control Point
             p0




    CGContextBeginPath(context);
    CGContextMoveToPoint(context, startPoint.x, startPoint.y);
Quadratic Bézier Curves
Single Control Point
              p0                                cp




                                           p1

CGContextAddQuadCurveToPoint(context, cp.x, cp.y, endPoint.x, endPoint.y);
Quadratic Bézier Curves
Single Control Point
            p0                                cp




                                         p1
     CGColorRef greenColor = [UIColor greenColor].CGColor;
     CGContextSetStrokeColorWithColor(context, greenColor);
     CGContextStrokePath(context);
Cubic Bézier Curves
Two Control Points


                          p0




   CGContextBeginPath(context);
   CGContextMoveToPoint(context, startPoint.x, startPoint.y);
Cubic Bézier Curves
Two Control Points
                                    cp1

                          p0

                                               cp2




                          p1
      CGContextAddCurveToPoint(context,
                               cp1.x, cp1.y,
                               cp2.x, cp2.y,
                               endPoint.x, endPoint.y);
Cubic Bézier Curves
Two Control Points
               -cp1                 cp1

                          p0

   -cp2                                        cp2




                          p1
      CGContextAddCurveToPoint(context,
                               -cp2.x, cp2.y,
                               -cp1.x, cp1.y,
                               endPoint.x, endPoint.y);
Cubic Bézier Curves
Two Control Points
               -cp1                   cp1

                            p0

   -cp2                                            cp2




                            p1
      CGColorRef fillColor = [UIColor redColor].CGColor;
      CGContextSetFillColorWithColor(context, fillColor);
      CGContextClosePath(context);
      CGContextDrawPath(context, kCGPathFillStroke);
Fill Rules
To fill, or not to fill

 • 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
Reusable Paths
CGPathRef and UIBezierPath

 • Paths are flushed from context when drawn
 • CGPath or UIBezierPath should be used when
   you need a reusable path
   CGMutablePathRef path = CGPathCreateMutable();
   CGPathMoveToPoint(path, NULL, 0, 55);
   CGPathAddQuadCurveToPoint(path, NULL, -50, 155, 0, 155);
   CGPathAddQuadCurveToPoint(path, NULL, 50, 155, 0, 55);

   CGContextAddPath(context, path);
   CGContextDrawPath(context, kCGPathFillStroke);

   CGPathRelease(path);
Transformations
Affine Transformations
Transforming the Coordinate System

 • 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


                                        X
Current Transformation Matrix
Modifying the CTM

 • CTM can be modified with the following:
   •   CGContextTranslateCTM
   •   CGContextScaleCTM
   •   CGContextRotateCTM

 • Additionally can create a CGAffineTransform
CGContextTranslateCTM
Moving the Origin Point

(0, 0)



               (100, 100)
CGContextTranslateCTM
Moving the Origin Point




          (0, 0)
                (0, 0)




CGContextTranslateCTM(context, 100.0f, 100.0f);
CGContextScaleCTM
Scaling the Coordinates

(0, 0)


         (200, 200)
CGContextScaleCTM
Scaling the Unit Size

(0, 0)




                  (200, 200)




      CGContextScaleCTM(context, 2.0f, 2.0f);
CGContextRotateCTM
CGContextRotateCTM




  CGContextRotateCTM(context, DEGREES(15));
Gradients
Gradients
Drawing 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




          Linear                   Radial
Creating a CGGradient
CGGradientRef

 • Gradients can be created using either:
   • CGGradientCreateWithColors
   • CGGradientCreateWithColorComponents
 • Both functions require the following:
   • CGColorSpace
   • Colors (components or array of CGColorRef)
   • CGFloat[] defining gradient color stops
CGGradientRef
Building the gradient code
// Define Colors
CGColorRef startColor = [UIColor greenColor].CGColor;
CGColorRef endColor = [UIColor yellowColor].CGColor;
NSMutableArray *colors = [NSMutableArray array];
[colors addObject:(id)startColor];
[colors addObject:(id)endColor];
	
// Define Color Locations
CGFloat locations[] = {0.0, 1.0};
	
// Create Gradient
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient =
     CGGradientCreateWithColors(colorSpace, (CFArrayRef)colors, locations);
	
// Define start and end points and draw gradient
CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
	
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
Gradient Examples
Images
Working with Images
CGImageRef

 • Quartz has broad support for images
 • Represented as CGImageRef
 • Can be drawn using:
   • CGContextDrawImage
   • CGContextDrawTiledImage
 • CGBitmapContext allows for dynamically
   building image data
CGImage vs UIImage
Which should I use?

 • Don’t draw in Quartz. Use UIImageView.
 • Choose UIImage over CGImage
    • Easier to load and cache image content
    • Provides methods for drawing
    • Is aware of flipped coordinate system
    • Easy to convert to and from CGImage
 • Use CGImage for more advanced cases
    • Cropping, scaling, masking
    • Dynamic image creation
Using Image Masks
Hiding behind a mask
Using Image Masks
    Hiding behind a mask




	   UIImage *maskImage = [UIImage imageNamed:@"round_mask"];
	   UIImage *jeffersonImage = [UIImage imageNamed:@"jefferson"];
	
	   CGImageRef   maskRef = maskImage.CGImage;
	   CGImageRef   imageMask = CGImageMaskCreate(CGImageGetWidth(maskRef),
	   	   	   	    	   	  	   	  	   	   	   CGImageGetHeight(maskRef),
	   	   	   	    	   	  	   	  	   	   	   CGImageGetBitsPerComponent(maskRef),
	   	   	   	    	   	  	   	  	   	   	   CGImageGetBitsPerPixel(maskRef),
	   	   	   	    	   	  	   	  	   	   	   CGImageGetBytesPerRow(maskRef),
	   	   	   	    	   	  	   	  	   	   	   CGImageGetDataProvider(maskRef), NULL, false);

	   CGImageRef masked = CGImageCreateWithMask(jeffersonImage, imageMask);
	   UIImage *maskedImage = [UIImage imageWithCGImage:masked];
Cropping Images
CGImageCreateWithImageInRect




UIImage *albumImage = [UIImage imageNamed:@"vh1"];
CGRect cropRect = CGRectMake(20.0f, 20.0f, 200.0f, 200.0f);
CGImageRef image = CGImageCreateWithImageInRect(albumImage.CGImage, cropRect);
	
CGRect imageRect = CGRectMake(0.0f, 0.0f, 200.0f, 200.0f);	
// Draw image in current context
[[UIImage imageWithCGImage:image] drawInRect:imageRect];
	
CGImageRelease(image);
Summary
• Quartz is a powerful, comprehensive
  drawing engine and API for Apple platforms
• Fairly steep learning curve, but consistent
  interface helps considerably
• Understanding is essential to building
  beautiful apps on Mac and iOS
Resources
Quartz 2D Programming Guide
http://developer.apple.com/
Quartz Demos
https://github.com/tapharmonic/QuartzDemos

Programming with Quartz
David Gelphman
Bunny Laden

More Related Content

What's hot

OpenGL L02-Transformations
OpenGL L02-TransformationsOpenGL L02-Transformations
OpenGL L02-TransformationsMohammad Shaker
 
Chameleon game engine
Chameleon game engineChameleon game engine
Chameleon game engineVictor Porof
 
HTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebHTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebRobin Hawkes
 
Introduction to open_gl_in_android
Introduction to open_gl_in_androidIntroduction to open_gl_in_android
Introduction to open_gl_in_androidtamillarasan
 
Python en la Plataforma ArcGIS
Python en la Plataforma ArcGISPython en la Plataforma ArcGIS
Python en la Plataforma ArcGISXander Bakker
 
Introduction to HTML5 Canvas
Introduction to HTML5 CanvasIntroduction to HTML5 Canvas
Introduction to HTML5 CanvasMindy McAdams
 
OpenGLES - Graphics Programming in Android
OpenGLES - Graphics Programming in Android OpenGLES - Graphics Programming in Android
OpenGLES - Graphics Programming in Android Arvind Devaraj
 
C graphics programs file
C graphics programs fileC graphics programs file
C graphics programs fileshubham kanojia
 
Kotlin Mullets
Kotlin MulletsKotlin Mullets
Kotlin MulletsJames Ward
 
OpenGL L07-Skybox and Terrian
OpenGL L07-Skybox and TerrianOpenGL L07-Skybox and Terrian
OpenGL L07-Skybox and TerrianMohammad Shaker
 
Writing a Space Shooter with HTML5 Canvas
Writing a Space Shooter with HTML5 CanvasWriting a Space Shooter with HTML5 Canvas
Writing a Space Shooter with HTML5 CanvasSteve Purkis
 

What's hot (17)

OpenGL L02-Transformations
OpenGL L02-TransformationsOpenGL L02-Transformations
OpenGL L02-Transformations
 
Chameleon game engine
Chameleon game engineChameleon game engine
Chameleon game engine
 
HTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebHTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the Web
 
Introduction to open_gl_in_android
Introduction to open_gl_in_androidIntroduction to open_gl_in_android
Introduction to open_gl_in_android
 
Python en la Plataforma ArcGIS
Python en la Plataforma ArcGISPython en la Plataforma ArcGIS
Python en la Plataforma ArcGIS
 
OpenGL L03-Utilities
OpenGL L03-UtilitiesOpenGL L03-Utilities
OpenGL L03-Utilities
 
Introduction to HTML5 Canvas
Introduction to HTML5 CanvasIntroduction to HTML5 Canvas
Introduction to HTML5 Canvas
 
HTML 5_Canvas
HTML 5_CanvasHTML 5_Canvas
HTML 5_Canvas
 
OpenGLES - Graphics Programming in Android
OpenGLES - Graphics Programming in Android OpenGLES - Graphics Programming in Android
OpenGLES - Graphics Programming in Android
 
2DCompsitionEngine
2DCompsitionEngine2DCompsitionEngine
2DCompsitionEngine
 
HTML 5 Canvas & SVG
HTML 5 Canvas & SVGHTML 5 Canvas & SVG
HTML 5 Canvas & SVG
 
C graphics programs file
C graphics programs fileC graphics programs file
C graphics programs file
 
AutoCAD
AutoCAD AutoCAD
AutoCAD
 
The Future of Qt Widgets
The Future of Qt WidgetsThe Future of Qt Widgets
The Future of Qt Widgets
 
Kotlin Mullets
Kotlin MulletsKotlin Mullets
Kotlin Mullets
 
OpenGL L07-Skybox and Terrian
OpenGL L07-Skybox and TerrianOpenGL L07-Skybox and Terrian
OpenGL L07-Skybox and Terrian
 
Writing a Space Shooter with HTML5 Canvas
Writing a Space Shooter with HTML5 CanvasWriting a Space Shooter with HTML5 Canvas
Writing a Space Shooter with HTML5 Canvas
 

Viewers also liked

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
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java DevelopersBob McCune
 
Master Video with AV Foundation
Master Video with AV FoundationMaster Video with AV Foundation
Master Video with AV FoundationBob McCune
 
Core Animation
Core AnimationCore Animation
Core AnimationBob McCune
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View ControllersBob McCune
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBob McCune
 
iOS design: a case study
iOS design: a case studyiOS design: a case study
iOS design: a case studyJohan Ronsse
 
Mastering Media with AV Foundation
Mastering Media with AV FoundationMastering Media with AV Foundation
Mastering Media with AV FoundationChris Adamson
 
Core Graphics & Core Animation
Core Graphics & Core AnimationCore Graphics & Core Animation
Core Graphics & Core AnimationAndreas Blick
 
Qipit Mobile Scanning Challenges Solutions
Qipit Mobile Scanning Challenges SolutionsQipit Mobile Scanning Challenges Solutions
Qipit Mobile Scanning Challenges Solutionsqipit
 
AVFoundation @ TACOW 2013 05 14
AVFoundation @ TACOW 2013 05 14AVFoundation @ TACOW 2013 05 14
AVFoundation @ TACOW 2013 05 14Ryder Mackay
 
iOS App Development Company
iOS App Development CompanyiOS App Development Company
iOS App Development CompanyMobilmindz
 
Introduction to AV Foundation
Introduction to AV FoundationIntroduction to AV Foundation
Introduction to AV FoundationChris Adamson
 
Top 10 trends every iOS app development company should follow
Top 10 trends every iOS app development company should followTop 10 trends every iOS app development company should follow
Top 10 trends every iOS app development company should followiMOBDEV Technologies Pvt. Ltd.
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core AnimationJohn Wilker
 
احترف صيانة الكمبيوتر
احترف صيانة الكمبيوتراحترف صيانة الكمبيوتر
احترف صيانة الكمبيوترtitifcom
 
If then vb2010
If then vb2010If then vb2010
If then vb2010Spy Seat
 
Rocking slideshow
Rocking slideshowRocking slideshow
Rocking slideshownycdoe
 
Jocelyn power point
Jocelyn power pointJocelyn power point
Jocelyn power pointnycdoe
 

Viewers also liked (20)

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
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java Developers
 
Master Video with AV Foundation
Master Video with AV FoundationMaster Video with AV Foundation
Master Video with AV Foundation
 
Core Animation
Core AnimationCore Animation
Core Animation
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View Controllers
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngine
 
iOS design: a case study
iOS design: a case studyiOS design: a case study
iOS design: a case study
 
Mastering Media with AV Foundation
Mastering Media with AV FoundationMastering Media with AV Foundation
Mastering Media with AV Foundation
 
Core Graphics & Core Animation
Core Graphics & Core AnimationCore Graphics & Core Animation
Core Graphics & Core Animation
 
Graphics Libraries
Graphics LibrariesGraphics Libraries
Graphics Libraries
 
Qipit Mobile Scanning Challenges Solutions
Qipit Mobile Scanning Challenges SolutionsQipit Mobile Scanning Challenges Solutions
Qipit Mobile Scanning Challenges Solutions
 
AVFoundation @ TACOW 2013 05 14
AVFoundation @ TACOW 2013 05 14AVFoundation @ TACOW 2013 05 14
AVFoundation @ TACOW 2013 05 14
 
iOS App Development Company
iOS App Development CompanyiOS App Development Company
iOS App Development Company
 
Introduction to AV Foundation
Introduction to AV FoundationIntroduction to AV Foundation
Introduction to AV Foundation
 
Top 10 trends every iOS app development company should follow
Top 10 trends every iOS app development company should followTop 10 trends every iOS app development company should follow
Top 10 trends every iOS app development company should follow
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
 
احترف صيانة الكمبيوتر
احترف صيانة الكمبيوتراحترف صيانة الكمبيوتر
احترف صيانة الكمبيوتر
 
If then vb2010
If then vb2010If then vb2010
If then vb2010
 
Rocking slideshow
Rocking slideshowRocking slideshow
Rocking slideshow
 
Jocelyn power point
Jocelyn power pointJocelyn power point
Jocelyn power point
 

Similar to Drawing with Quartz on iOS

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
 
[C++ GUI Programming with Qt4] chap8
[C++ GUI Programming with Qt4] chap8[C++ GUI Programming with Qt4] chap8
[C++ GUI Programming with Qt4] chap8Picker Weng
 
Rotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billyRotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billynimbleltd
 
The Ring programming language version 1.9 book - Part 114 of 210
The Ring programming language version 1.9 book - Part 114 of 210The Ring programming language version 1.9 book - Part 114 of 210
The Ring programming language version 1.9 book - Part 114 of 210Mahmoud Samir Fayed
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring CanvasKevin Hoyt
 
Text Layout With Core Text
Text Layout With Core TextText Layout With Core Text
Text Layout With Core TextDavid Ding
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IICS
 
Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器vito jeng
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3Droxlu
 
The Ring programming language version 1.10 book - Part 125 of 212
The Ring programming language version 1.10 book - Part 125 of 212The Ring programming language version 1.10 book - Part 125 of 212
The Ring programming language version 1.10 book - Part 125 of 212Mahmoud Samir Fayed
 
Scripting Your Qt Application
Scripting Your Qt ApplicationScripting Your Qt Application
Scripting Your Qt Applicationaccount inactive
 
MSc Thesis Defense Presentation
MSc Thesis Defense PresentationMSc Thesis Defense Presentation
MSc Thesis Defense PresentationMostafa Elhoushi
 

Similar to Drawing with Quartz on iOS (20)

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
 
[C++ GUI Programming with Qt4] chap8
[C++ GUI Programming with Qt4] chap8[C++ GUI Programming with Qt4] chap8
[C++ GUI Programming with Qt4] chap8
 
Rotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billyRotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billy
 
The Ring programming language version 1.9 book - Part 114 of 210
The Ring programming language version 1.9 book - Part 114 of 210The Ring programming language version 1.9 book - Part 114 of 210
The Ring programming language version 1.9 book - Part 114 of 210
 
Matlab robotics toolbox
Matlab robotics toolboxMatlab robotics toolbox
Matlab robotics toolbox
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 
Css5 canvas
Css5 canvasCss5 canvas
Css5 canvas
 
Single qubit-gates operations
Single qubit-gates operationsSingle qubit-gates operations
Single qubit-gates operations
 
Text Layout With Core Text
Text Layout With Core TextText Layout With Core Text
Text Layout With Core Text
 
Chapter-3.pdf
Chapter-3.pdfChapter-3.pdf
Chapter-3.pdf
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part I
 
Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3D
 
Multi qubit entanglement
Multi qubit entanglementMulti qubit entanglement
Multi qubit entanglement
 
The Ring programming language version 1.10 book - Part 125 of 212
The Ring programming language version 1.10 book - Part 125 of 212The Ring programming language version 1.10 book - Part 125 of 212
The Ring programming language version 1.10 book - Part 125 of 212
 
Scripting Your Qt Application
Scripting Your Qt ApplicationScripting Your Qt Application
Scripting Your Qt Application
 
Unit 2 notes
Unit 2 notesUnit 2 notes
Unit 2 notes
 
MSc Thesis Defense Presentation
MSc Thesis Defense PresentationMSc Thesis Defense Presentation
MSc Thesis Defense Presentation
 
Canvas
CanvasCanvas
Canvas
 
Canvas
CanvasCanvas
Canvas
 

Recently uploaded

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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
🐬 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
 
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
 
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
 

Recently uploaded (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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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 ...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
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...
 

Drawing with Quartz on iOS

  • 1. Drawing with Quartz on iOS http://bobmccune.com http://tapharmonic.com
  • 2. Agenda • Overview of the Quartz framework • What is it? • When do you need it? • Key framework functionality: • Contexts and Paths • Drawing lines, curves, and images • Applying transformations • Recipes and Examples
  • 4. What is Quartz? Wasn’t this talk supposed to be about Core Graphics? • 2D drawing engine for Mac and iOS based on the PDF imaging model • Graphics API to produce lines, curves, transformations, gradients, etc. • Uses painters model for drawing operations Drawing Order Result
  • 5. When do I need it? Isn’t this what graphic designers are for? • Always build your UI from images • Better performance and caching • Easier to create and maintain • Keeps your graphic designers employed • Always, always, always use images... ...until you can’t
  • 6.
  • 7.
  • 8.
  • 9.
  • 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];
  • 12. Understanding the Syntax Dude, where’s my objects? Objective-C CGContext *context = [[CGContext alloc] init]; Quartz is not an Objective-C API [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);
  • 13. Quartz is Consistent Naming Conventions Functions always use the following convention: <Type><Action>(<Object>, <Arguments); CGContextMoveToPoint(context, 12.0f, 12.0f); CGPathAddLineToPoint(path, NULL, 22.0f, 100.0f); CGPDFContextClose(context);
  • 15. Quartz Graphics Contexts The Canvas • 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
  • 16. Quartz Coordinate System Drawing Orientation • Current Transformation Matrix (CTM) defines the coordinate system • Coordinate system varies on Mac and iOS y Positive 0, 0 x x 0, 0 y Positive Mac OS X iOS
  • 17. CGContext Drawing Quartz Points • Drawing is p0 defined in terms of points • Points are abstract, infinitely thin • Points live in p1 User Space
  • 18. Points are Device-Independent Think in points not pixels p0 p1
  • 19. CGContext Drawing CGContextRef • CGContextRef is the drawing context • Created by UIKit and AppKit • Get a pointer reference to it: iOS CGContextRef context = UIGraphicsGetCurrentContext(); Mac NSGraphicsContext *current = [NSGraphicsContext currentContext]; CGContextRef context = (CGContextRef)[current graphicsPort];
  • 21. Getting Started Where do I draw? @implementation HelloQuartzViewController - (void)drawBackground:(UIGestureRecognizer *)recognizer { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, THRandomColor()); CGContextFillRect(context, self.view.bounds); } @end
  • 22. Getting Started Where do I draw? @implementation HelloQuartzViewController - (void)drawBackground:(UIGestureRecognizer *)recognizer { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, THRandomColor()); CGContextFillRect(context, self.view.bounds); } @end @implementation HelloQuartzView - (void)drawRect:(CGRect)rect { } @end
  • 23. Getting Started Where do I draw? @implementation HelloQuartzViewController - (void)drawBackground:(UIGestureRecognizer *)recognizer { // Trigger call to HelloQuartzView's drawRect method (if needed) [self.helloView setNeedsDisplay]; } @end @implementation HelloQuartzView - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, THRandomColor()); CGContextFillRect(context, rect); } @end
  • 25. CGContext Drawing Defining Paths (0, 0) (100, 100) CGRect rect = CGRectMake(0, 0, 100, 100); CGContextAddRect(context, rect);
  • 26. CGContext Drawing Defining Paths (0, 0) (100, 100) CGRect rect = CGRectMake(0, 0, 100, 100); CGContextAddEllipseInRect(context, rect);
  • 27. CGContext Drawing Defining Paths (0, 0) (100, 100) CGContextSetStrokeColorWithColor(context, white); CGContextDrawPath(context, kCGPathStroke);
  • 28. CGContext Drawing Defining Paths (0, 0) (100, 100) CGContextSetFillColorWithColor(context, yellow); CGContextDrawPath(context, kCGPathFill);
  • 29. CGContext Drawing Defining Paths (0, 0) (100, 100) CGContextDrawPath(context, kCGPathFillStroke);
  • 30. Defining Colors CGColorRef • Colors must be defined before drawing • Fill Colors • CGContextSetFillColor • CGContextSetFillColorWithColor • CGContextSetRGBFillColor • Stroke Colors • CGContextSetStrokeColor • CGContextSetStrokeColorWithColor • CGContextSetRGBStrokeColor
  • 31. Defining Colors CGColor vs UIColor • CGColor is the native Quartz color type • UIColor is the native UIKit color type • Use UIColor in almost all cases • Easier to create • Autoreleased convenience initializers • Named color initializers • Easy to convert to and from CGColor CGColorRef redColor = [UIColor redColor].CGColor; CGContextSetFillColorWithColor(context, redColor);
  • 32. Drawing Lines Defining Paths • 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.Optionally close the path 5.Draw Path
  • 33. CGContext Drawing Defining Paths CGContextBeginPath(context); CGContextMoveToPoint(context, 0.0f, 0.0f);
  • 34. CGContext Drawing Defining Paths CGContextAddLineToPoint(context, 0.0f, 4.0f);
  • 35. CGContext Drawing Defining Paths CGContextAddLineToPoint(context, 4.0f, 4.0f);
  • 36. CGContext Drawing Defining Paths CGContextAddLineToPoint(context, 4.0f, 0.0f);
  • 37. CGContext Drawing Defining Paths CGContextClosePath(context);
  • 38. CGContext Drawing Defining Paths CGColorRef color = [UIColor whiteColor].CGColor; CGContextSetFillColorWithColor(context, color);
  • 39. CGContext Drawing Defining Paths CGContextDrawPath(context, kCGPathFill);
  • 41. Drawing Arcs Defining Paths • Arcs define circle segments • Arcs are defined with the following: • Center point x, y coordinates • Radius • Start and stop angles (in radians) • Direction (clockwise or counter-clockwise) • Created using: • CGContextAddArc • CGContextAddArcToPoint
  • 42. UIBezierPath More iOS-friendly solution • Arc functions are not aware of flipped coordinate system • Need to think upside down • Transform coordinate system before using • UIBezierPath provides a lightweight wrapper over Quartz path functionality • Access to underlying path with CGPath property • Easier to use UIBezierPath on iOS
  • 43. Drawing Arcs Defining Paths UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:radius startAngle:0 endAngle:DEGREES(90) clockwise:NO]; CGContextAddPath(context, path.CGPath);
  • 44. Quadratic Bézier Curves Single Control Point p0 CGContextBeginPath(context); CGContextMoveToPoint(context, startPoint.x, startPoint.y);
  • 45. Quadratic Bézier Curves Single Control Point p0 cp p1 CGContextAddQuadCurveToPoint(context, cp.x, cp.y, endPoint.x, endPoint.y);
  • 46. Quadratic Bézier Curves Single Control Point p0 cp p1 CGColorRef greenColor = [UIColor greenColor].CGColor; CGContextSetStrokeColorWithColor(context, greenColor); CGContextStrokePath(context);
  • 47. Cubic Bézier Curves Two Control Points p0 CGContextBeginPath(context); CGContextMoveToPoint(context, startPoint.x, startPoint.y);
  • 48. Cubic Bézier Curves Two Control Points cp1 p0 cp2 p1 CGContextAddCurveToPoint(context, cp1.x, cp1.y, cp2.x, cp2.y, endPoint.x, endPoint.y);
  • 49. Cubic Bézier Curves Two Control Points -cp1 cp1 p0 -cp2 cp2 p1 CGContextAddCurveToPoint(context, -cp2.x, cp2.y, -cp1.x, cp1.y, endPoint.x, endPoint.y);
  • 50. Cubic Bézier Curves Two Control Points -cp1 cp1 p0 -cp2 cp2 p1 CGColorRef fillColor = [UIColor redColor].CGColor; CGContextSetFillColorWithColor(context, fillColor); CGContextClosePath(context); CGContextDrawPath(context, kCGPathFillStroke);
  • 51. Fill Rules To fill, or not to fill • 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
  • 52. Reusable Paths CGPathRef and UIBezierPath • Paths are flushed from context when drawn • CGPath or UIBezierPath should be used when you need a reusable path CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 0, 55); CGPathAddQuadCurveToPoint(path, NULL, -50, 155, 0, 155); CGPathAddQuadCurveToPoint(path, NULL, 50, 155, 0, 55); CGContextAddPath(context, path); CGContextDrawPath(context, kCGPathFillStroke); CGPathRelease(path);
  • 54. Affine Transformations Transforming the Coordinate System • 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 X
  • 55. Current Transformation Matrix Modifying the CTM • CTM can be modified with the following: • CGContextTranslateCTM • CGContextScaleCTM • CGContextRotateCTM • Additionally can create a CGAffineTransform
  • 56. CGContextTranslateCTM Moving the Origin Point (0, 0) (100, 100)
  • 57. CGContextTranslateCTM Moving the Origin Point (0, 0) (0, 0) CGContextTranslateCTM(context, 100.0f, 100.0f);
  • 59. CGContextScaleCTM Scaling the Unit Size (0, 0) (200, 200) CGContextScaleCTM(context, 2.0f, 2.0f);
  • 63. Gradients Drawing 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 Linear Radial
  • 64. Creating a CGGradient CGGradientRef • Gradients can be created using either: • CGGradientCreateWithColors • CGGradientCreateWithColorComponents • Both functions require the following: • CGColorSpace • Colors (components or array of CGColorRef) • CGFloat[] defining gradient color stops
  • 65. CGGradientRef Building the gradient code // Define Colors CGColorRef startColor = [UIColor greenColor].CGColor; CGColorRef endColor = [UIColor yellowColor].CGColor; NSMutableArray *colors = [NSMutableArray array]; [colors addObject:(id)startColor]; [colors addObject:(id)endColor]; // Define Color Locations CGFloat locations[] = {0.0, 1.0}; // Create Gradient CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)colors, locations); // Define start and end points and draw gradient CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect)); CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect)); CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
  • 68. Working with Images CGImageRef • Quartz has broad support for images • Represented as CGImageRef • Can be drawn using: • CGContextDrawImage • CGContextDrawTiledImage • CGBitmapContext allows for dynamically building image data
  • 69. CGImage vs UIImage Which should I use? • Don’t draw in Quartz. Use UIImageView. • Choose UIImage over CGImage • Easier to load and cache image content • Provides methods for drawing • Is aware of flipped coordinate system • Easy to convert to and from CGImage • Use CGImage for more advanced cases • Cropping, scaling, masking • Dynamic image creation
  • 70. Using Image Masks Hiding behind a mask
  • 71. Using Image Masks Hiding behind a mask UIImage *maskImage = [UIImage imageNamed:@"round_mask"]; UIImage *jeffersonImage = [UIImage imageNamed:@"jefferson"]; CGImageRef maskRef = maskImage.CGImage; CGImageRef imageMask = CGImageMaskCreate(CGImageGetWidth(maskRef), CGImageGetHeight(maskRef), CGImageGetBitsPerComponent(maskRef), CGImageGetBitsPerPixel(maskRef), CGImageGetBytesPerRow(maskRef), CGImageGetDataProvider(maskRef), NULL, false); CGImageRef masked = CGImageCreateWithMask(jeffersonImage, imageMask); UIImage *maskedImage = [UIImage imageWithCGImage:masked];
  • 72. Cropping Images CGImageCreateWithImageInRect UIImage *albumImage = [UIImage imageNamed:@"vh1"]; CGRect cropRect = CGRectMake(20.0f, 20.0f, 200.0f, 200.0f); CGImageRef image = CGImageCreateWithImageInRect(albumImage.CGImage, cropRect); CGRect imageRect = CGRectMake(0.0f, 0.0f, 200.0f, 200.0f); // Draw image in current context [[UIImage imageWithCGImage:image] drawInRect:imageRect]; CGImageRelease(image);
  • 73. Summary • Quartz is a powerful, comprehensive drawing engine and API for Apple platforms • Fairly steep learning curve, but consistent interface helps considerably • Understanding is essential to building beautiful apps on Mac and iOS
  • 74. Resources Quartz 2D Programming Guide http://developer.apple.com/ Quartz Demos https://github.com/tapharmonic/QuartzDemos Programming with Quartz David Gelphman Bunny Laden