0% found this document useful (0 votes)
5 views90 pages

Quartz 2d Programming Guide Download

The document is the Quartz 2D Programming Guide, which provides comprehensive information on using Quartz 2D for graphics and animation in macOS and iOS. It covers various topics such as graphics contexts, paths, color management, transformations, and PDF document creation. The guide is intended for application developers and includes detailed instructions and examples for implementing graphics features.

Uploaded by

njillahresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views90 pages

Quartz 2d Programming Guide Download

The document is the Quartz 2D Programming Guide, which provides comprehensive information on using Quartz 2D for graphics and animation in macOS and iOS. It covers various topics such as graphics contexts, paths, color management, transformations, and PDF document creation. The guide is intended for application developers and includes detailed instructions and examples for implementing graphics features.

Uploaded by

njillahresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Quartz 2d Programming Guide download

https://ebookbell.com/product/quartz-2d-programming-guide-2463152

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Programming With Quartz 2d And Pdf Graphics In Mac Os X 1st Edition


David Gelphman

https://ebookbell.com/product/programming-with-quartz-2d-and-pdf-
graphics-in-mac-os-x-1st-edition-david-gelphman-2382698

Quartz 2d Graphics For Mac Os X Developers R Scott Thompson

https://ebookbell.com/product/quartz-2d-graphics-for-mac-os-x-
developers-r-scott-thompson-983430

Quartz Mountain The Lost Realm Book 1 The Lost Realm Series Audrey
Lynn

https://ebookbell.com/product/quartz-mountain-the-lost-realm-
book-1-the-lost-realm-series-audrey-lynn-55442972

Quartz Deposits Mineralogy And Analytics 1st Edition Jens Gtze Auth

https://ebookbell.com/product/quartz-deposits-mineralogy-and-
analytics-1st-edition-jens-gtze-auth-4399110
Quartz Job Scheduling Framework Building Open Source Enterprise
Applications 1st Edition Chuck Cavaness

https://ebookbell.com/product/quartz-job-scheduling-framework-
building-open-source-enterprise-applications-1st-edition-chuck-
cavaness-919256

The Quartz Crystal Microbalance In Soft Matter Research Fundamentals


And Modeling 1st Edition Diethelm Johannsmann Auth

https://ebookbell.com/product/the-quartz-crystal-microbalance-in-soft-
matter-research-fundamentals-and-modeling-1st-edition-diethelm-
johannsmann-auth-4931394

Cool How The Brains Hidden Quest For Cool Drives Our Economy And
Shapes Our World Steven Quartz

https://ebookbell.com/product/cool-how-the-brains-hidden-quest-for-
cool-drives-our-economy-and-shapes-our-world-steven-quartz-5026410

Learning Quartz Composer A Handson Guide To Creating Motion Graphics


With Quartz Composer Graham Robinson

https://ebookbell.com/product/learning-quartz-composer-a-handson-
guide-to-creating-motion-graphics-with-quartz-composer-graham-
robinson-10303858

Understanding Quartz Crystals And Oscillators Ramn M Cerda

https://ebookbell.com/product/understanding-quartz-crystals-and-
oscillators-ramn-m-cerda-10566446
Quartz 2D Programming Guide
Graphics & Animation: 2D Drawing

2010-11-19
Even though Apple has reviewed this document,
APPLE MAKES NO WARRANTY OR REPRESENTATION,
Apple Inc. EITHER EXPRESS OR IMPLIED, WITH RESPECT TO
© 2001, 2010 Apple Inc. THIS DOCUMENT, ITS QUALITY, ACCURACY,
MERCHANTABILITY, OR FITNESS FOR A PARTICULAR
All rights reserved. PURPOSE. AS A RESULT, THIS DOCUMENT IS
PROVIDED “AS IS,” AND YOU, THE READER, ARE
ASSUMING THE ENTIRE RISK AS TO ITS QUALITY
No part of this publication may be reproduced, AND ACCURACY.
stored in a retrieval system, or transmitted, in IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT,
any form or by any means, mechanical, INDIRECT, SPECIAL, INCIDENTAL, OR
electronic, photocopying, recording, or CONSEQUENTIAL DAMAGES RESULTING FROM ANY
DEFECT OR INACCURACY IN THIS DOCUMENT, even
otherwise, without prior written permission of if advised of the possibility of such damages.
Apple Inc., with the following exceptions: Any THE WARRANTY AND REMEDIES SET FORTH ABOVE
person is hereby authorized to store ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL
documentation on a single computer for OR WRITTEN, EXPRESS OR IMPLIED. No Apple
dealer, agent, or employee is authorized to make
personal use only and to print copies of any modification, extension, or addition to this
documentation for personal use provided that warranty.
the documentation contains Apple’s copyright Some states do not allow the exclusion or limitation
of implied warranties or liability for incidental or
notice. consequential damages, so the above limitation or
exclusion may not apply to you. This warranty gives
The Apple logo is a trademark of Apple Inc. you specific legal rights, and you may also have
other rights which vary from state to state.
No licenses, express or implied, are granted
with respect to any of the technology described
in this document. Apple retains all intellectual
property rights associated with the technology
described in this document. This document is
intended to assist application developers to
develop applications only for Apple-labeled
computers.
Apple Inc.
1 Infinite Loop
Cupertino, CA 95014
408-996-1010

Apple, the Apple logo, Cocoa, ColorSync, eMac,


Mac, Mac OS, Objective-C, Pages, Quartz,
QuickTime, Spaces, Tiger, and Xcode are
trademarks of Apple Inc., registered in the
United States and other countries.
Adobe, Acrobat, and PostScript are trademarks
or registered trademarks of Adobe Systems
Incorporated in the U.S. and/or other countries.
Adobe, Acrobat, and PostScript are trademarks
or registered trademarks of Adobe Systems
Incorporated in the U.S. and/or other countries.
Adobe, Acrobat, and PostScript are trademarks
or registered trademarks of Adobe Systems
Incorporated in the U.S. and/or other countries.
Helvetica is a registered trademark of
Heidelberger Druckmaschinen AG, available
from Linotype Library GmbH.
IOS is a trademark or registered trademark of
Cisco in the U.S. and other countries and is used
under license.
OpenGL is a registered trademark of Silicon
Graphics, Inc.
Contents

Introduction Introduction 15

Who Should Read This Document? 15


Organization of This Document 15
See Also 16

Chapter 1 Overview of Quartz 2D 19

The Page 19
Drawing Destinations: The Graphics Context 20
Quartz 2D Opaque Data Types 22
Graphics States 23
Quartz 2D Coordinate Systems 24
Memory Management: Object Ownership 26

Chapter 2 Graphics Contexts 29

Drawing to a View Graphics Context in iOS 29


Creating a Window Graphics Context in Mac OS X 29
Creating a PDF Graphics Context 31
Creating a Bitmap Graphics Context 35
Supported Pixel Formats 39
Anti-Aliasing 40
Obtaining a Graphics Context for Printing 41

Chapter 3 Paths 43

Path Creation and Path Painting 43


The Building Blocks 44
Points 45
Lines 45
Arcs 45
Curves 47
Closing a Subpath 48
Ellipses 49
Rectangles 49
Creating a Path 50
Painting a Path 51
Parameters That Affect Stroking 51
Functions for Stroking a Path 54
Filling a Path 54
Setting Blend Modes 55

3
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CONTENTS

Clipping to a Path 64

Chapter 4 Color and Color Spaces 67

About Color and Color Spaces 67


The Alpha Value 68
Creating Color Spaces 69
Creating Device-Independent Color Spaces 70
Creating Generic Color Spaces 70
Creating Device Color Spaces 71
Creating Indexed and Pattern Color Spaces 71
Setting and Creating Colors 71
Setting Rendering Intent 73

Chapter 5 Transforms 75

About Quartz Transformation Functions 75


Modifying the Current Transformation Matrix 76
Creating Affine Transforms 80
Evaluating Affine Transforms 81
Getting the User to Device Space Transform 82
The Math Behind the Matrices 82

Chapter 6 Patterns 85

The Anatomy of a Pattern 85


Colored Patterns and Stencil (Uncolored) Patterns 88
Tiling 89
How Patterns Work 89
Painting Colored Patterns 90
Write a Callback Function That Draws a Colored Pattern Cell 90
Set Up the Colored Pattern Color Space 91
Set Up the Anatomy of the Colored Pattern 92
Specify the Colored Pattern as a Fill or Stroke Pattern 93
Draw With the Colored Pattern 93
A Complete Colored Pattern Painting Function 93
Painting Stencil Patterns 95
Write a Callback Function That Draws a Stencil Pattern Cell 95
Set Up the Stencil Pattern Color Space 96
Set Up the Anatomy of the Stencil Pattern 97
Specify the Stencil Pattern as a Fill or Stroke Pattern 97
Drawing with the Stencil Pattern 98
A Complete Stencil Pattern Painting Function 98

4
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CONTENTS

Chapter 7 Shadows 101

How Shadows Work 102


Shadow Drawing Conventions Vary Based on the Context 102
Painting with Shadows 102

Chapter 8 Gradients 105

Axial and Radial Gradient Examples 105


A Comparison of CGShading and CGGradient Objects 108
Extending Color Beyond the End of a Gradient 109
Using a CGGradient Object 110
Using a CGShading Object 113
Painting an Axial Gradient Using a CGShading Object 114
Painting a Radial Gradient Using a CGShading Object 120
See Also 124

Chapter 9 Transparency Layers 125

How Transparency Layers Work 126


Painting to a Transparency Layer 126

Chapter 10 Data Management in Quartz 2D 129

Moving Data into Quartz 2D 130


Moving Data out of Quartz 2D 131
Moving Data Between Quartz 2D and Core Image in Mac OS X 132

Chapter 11 Bitmap Images and Image Masks 135

About Bitmap Images and Image Masks 135


Bitmap Image Information 136
Decode Array 137
Pixel Format 137
Color Spaces and Bitmap Layout 137
Creating Images 139
Creating an Image From Part of a Larger Image 140
Creating an Image from a Bitmap Graphics Context 142
Creating an Image Mask 142
Masking Images 143
Masking an Image with an Image Mask 143
Masking an Image with an Image 145
Masking an Image with Color 146
Masking an Image by Clipping the Context 149
Using Blend Modes with Images 151
Normal Blend Mode 152

5
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CONTENTS

Multiply Blend Mode 153


Screen Blend Mode 153
Overlay Blend Mode 154
Darken Blend Mode 155
Lighten Blend Mode 155
Color Dodge Blend Mode 156
Color Burn Blend Mode 156
Soft Light Blend Mode 157
Hard Light Blend Mode 158
Difference Blend Mode 159
Exclusion Blend Mode 159
Hue Blend Mode 160
Saturation Blend Mode 160
Color Blend Mode 161
Luminosity Blend Mode 161

Chapter 12 Core Graphics Layer Drawing 163

How Layer Drawing Works 163


Drawing with a Layer 165
Create a CGLayer Object Initialized with an Existing Graphics Context 165
Get a Graphics Context for the Layer 165
Draw to the CGLayer Graphics Context 166
Draw the Layer to the Destination Graphics Context 166
Example: Using Multiple CGLayer Objects to Draw a Flag 167

Chapter 13 PDF Document Creation, Viewing, and Transforming 173

Opening and Viewing a PDF 174


Creating a Transform for a PDF Page 175
Creating a PDF File 178
Adding Links 180
Protecting PDF Content 180

Chapter 14 PDF Document Parsing 181

Inspecting PDF Document Structure 181


Parsing PDF Content 183
Write Callbacks for Operators 184
Create and Set Up the Operator Table 185
Open the PDF Document 185
Scan the Content Stream for Each Page 186

Chapter 15 PostScript Conversion 189

Writing Callbacks 189

6
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CONTENTS

Filling In a Callbacks Structure 190


Creating a PostScript Converter Object 191
Creating Data Provider and Data Consumer Objects 191
Performing the Conversion 191

Chapter 16 Text 193

How Quartz 2D Draws Text 193


Controlling How Text Looks 194
Drawing Text 195
Measuring Text Before Drawing 198
Copying Font Variations 199
PostScript Fonts 199

Glossary 201

Document Revision History 203

7
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CONTENTS

8
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
Figures, Tables, and Listings

Chapter 1 Overview of Quartz 2D 19

Figure 1-1 The painter’s model 20


Figure 1-2 Quartz drawing destinations 21
Figure 1-3 Opaque data types are the basis of drawing primitives in Quartz 2D 22
Figure 1-4 The Quartz coordinate system 24
Figure 1-5 Modifying the coordinate system creates a mirrored image. 26
Table 1-1 Parameters that are associated with the graphics state 24

Chapter 2 Graphics Contexts 29

Figure 2-1 A view in the Cocoa framework that contains Quartz drawing 30
Figure 2-2 A PDF created by using CGPDFContextCreateWithURL 32
Figure 2-3 An image created from a bitmap graphics context and drawn to a window graphics
context 39
Figure 2-4 A comparison of aliased and anti-aliasing drawing 41
Table 2-1 Pixel formats supported for bitmap graphics contexts 39
Listing 2-1 Drawing to a window graphics context 30
Listing 2-2 Calling CGPDFContextCreateWithURL to create a PDF graphics context 32
Listing 2-3 Calling CGPDFContextCreate to create a PDF graphics context 33
Listing 2-4 Drawing to a PDF graphics context 34
Listing 2-5 Creating a bitmap graphics context 37
Listing 2-6 Drawing to a bitmap graphics context 38

Chapter 3 Paths 43

Figure 3-1 Quartz supports path-based drawing 43


Figure 3-2 A path that contains two shapes, or subpaths 44
Figure 3-3 A clipping area constrains drawing 44
Figure 3-4 Multiple paths; each path contains a randomly generated circle 46
Figure 3-5 Defining an arc with two tangent lines and a radius 46
Figure 3-6 Multiple paths; each path contains a randomly generated curve 47
Figure 3-7 A cubic Bézier curve uses two control points 48
Figure 3-8 A quadratic Bézier curve uses one control point 48
Figure 3-9 Multiple paths; each path contains a randomly generated ellipse 49
Figure 3-10 Multiple paths; each path contains a randomly generated rectangle 50
Figure 3-11 Examples of line dash patterns 53
Figure 3-12 Concentric circles filled using different fill rules 55
Figure 3-13 The rectangles painted in the foreground 56
Figure 3-14 The rectangles painted in the background 56
Figure 3-15 Rectangles painted using normal blend mode 57
Figure 3-16 Rectangles painted using multiply blend mode 57

9
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
FIGURES, TABLES, AND LISTINGS

Figure 3-17 Rectangles painted using screen blend mode 58


Figure 3-18 Rectangles painted using overlay blend mode 58
Figure 3-19 Rectangles painted using darken blend mode 59
Figure 3-20 Rectangles painted using lighten blend mode 59
Figure 3-21 Rectangles painted using color dodge blend mode 60
Figure 3-22 Rectangles painted using color burn blend mode 60
Figure 3-23 Rectangles painted using soft light blend mode 61
Figure 3-24 Rectangles painted using hard light blend mode 61
Figure 3-25 Rectangles painted using difference blend mode 62
Figure 3-26 Rectangles painted using exclusion blend mode 62
Figure 3-27 Rectangles painted using hue blend mode 63
Figure 3-28 Rectangles painted using saturation blend mode 63
Figure 3-29 Rectangles painted using color blend mode 64
Figure 3-30 Rectangles painted using luminosity blend mode 64
Table 3-1 Parameters that affect how Quartz strokes the current path 52
Table 3-2 Line join styles 52
Table 3-3 Line cap styles 53
Table 3-4 Functions that stroke paths 54
Table 3-5 Functions that fill paths 55
Table 3-6 Functions that clip the graphics context 65
Listing 3-1 Setting up a circular clip area 65

Chapter 4 Color and Color Spaces 67

Figure 4-1 Applying a BGR and an RGB color profile to the same image 68
Figure 4-2 A comparison of large rectangles painted using various alpha values 68
Figure 4-3 A comparison of global alpha values 69
Figure 4-4 A CMYK fill color and an RGB stroke color 72
Table 4-1 Color values in different color spaces 67
Table 4-2 Color-setting functions 72

Chapter 5 Transforms 75

Figure 5-1 Applying scaling and rotation 75


Figure 5-2 An image that is not transformed 76
Figure 5-3 A translated image 77
Figure 5-4 A rotated image 77
Figure 5-5 A scaled image 78
Figure 5-6 An image that is translated and rotated 79
Figure 5-7 An image that is translated, scaled, and then rotated 79
Figure 5-8 An image that is rotated, scaled, and then translated 80
Table 5-1 Affine transform functions for translation, rotation, and scaling 81

10
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
FIGURES, TABLES, AND LISTINGS

Chapter 6 Patterns 85

Figure 6-1 A pattern drawn to a window 85


Figure 6-2 A pattern cell 85
Figure 6-3 Pattern cells with black rectangles drawn to show the bounds of each cell 86
Figure 6-4 Spacing between pattern cells 86
Figure 6-5 A scaled pattern cell 87
Figure 6-6 A rotated pattern cell 87
Figure 6-7 A translated pattern cell 88
Figure 6-8 A colored pattern has inherent color 88
Figure 6-9 A stencil pattern does not have inherent color 88
Figure 6-10 A stencil pattern cell 96
Listing 6-1 A drawing callback that draws a colored pattern cell 91
Listing 6-2 Creating a base pattern color space 91
Listing 6-3 The CGPatternCreate function prototype 92
Listing 6-4 A function that paints a colored pattern 93
Listing 6-5 A drawing callback that draws a stencil pattern cell 96
Listing 6-6 Code that creates a pattern color space for a stencil pattern 96
Listing 6-7 Code that sets opacity for a colored pattern 97
Listing 6-8 A function that paints a stencil pattern 98

Chapter 7 Shadows 101

Figure 7-1 A shadow 101


Figure 7-2 A shadow with no blur and another with a soft edge 101
Figure 7-3 A colored shadow and a gray shadow 103
Listing 7-1 A function that sets up shadows 103

Chapter 8 Gradients 105

Figure 8-1 An axial gradient along a 45 degree axis 105


Figure 8-2 An axial gradient created with seven locations and colors 106
Figure 8-3 A radial gradient that varies between two circles 106
Figure 8-4 A radial gradient created by varying only the alpha component 107
Figure 8-5 A radial gradient that varies between a point and a circle 107
Figure 8-6 Nested radial gradients 108
Figure 8-7 Extending an axial gradient 109
Figure 8-8 Extending a radial gradient 110
Figure 8-9 A radial gradient painted using a CGGradient object 112
Figure 8-10 An axial gradient with three locations 113
Figure 8-11 An axial gradient that is clipped and painted 115
Figure 8-12 A radial gradient creating using a CGShading object 120
Table 8-1 Differences between CGShading and CGGradient objects 109
Listing 8-1 Creating a CGGradient object 111
Listing 8-2 Painting an axial gradient using a CGGradient object 111

11
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
FIGURES, TABLES, AND LISTINGS

Listing 8-3 Painting a radial gradient using a CGGradient object 111


Listing 8-4 The variables used to create a radial gradient by varying alpha 112
Listing 8-5 The variables used to create a gray gradient 112
Listing 8-6 Computing color component values 116
Listing 8-7 Creating a CGFunction object 116
Listing 8-8 Creating a CGShading object for an axial gradient 117
Listing 8-9 Adding a semicircle clip to the graphics context 118
Listing 8-10 Releasing objects 118
Listing 8-11 Painting an axial gradient using a CGShading object 118
Listing 8-12 Computing color component values 121
Listing 8-13 Creating a CGShading object for a radial gradient 121
Listing 8-14 Code that releases objects 122
Listing 8-15 A routine that paints a radial gradient using a CGShading object 122

Chapter 9 Transparency Layers 125

Figure 9-1 Three circles as a composite in a transparency layer 125


Figure 9-2 Three circles painted as separate entities 126
Figure 9-3 Three rectangles painted to a transparency layer 127
Listing 9-1 Painting to a transparency layer 127

Chapter 10 Data Management in Quartz 2D 129

Figure 10-1 Moving data to and from Quartz 2D in Mac OS X 130


Table 10-1 Functions that move data into Quartz 2D 131
Table 10-2 Functions that move data out of Quartz 2D 132

Chapter 11 Bitmap Images and Image Masks 135

Figure 11-1 Bitmap images 135


Figure 11-2 32-bit and 16-bit pixel formats for CMYK and RGB color spaces in Quartz 2D 139
Figure 11-3 A subimage created from a larger image 141
Figure 11-4 An image, a subimage taken from it and drawn so it’s enlarged 141
Figure 11-5 The original image 144
Figure 11-6 An image mask 144
Figure 11-7 The image that results from applying the image mask to the original image 145
Figure 11-8 The image that results from masking the original image with an image 146
Figure 11-9 Chroma key masking 146
Figure 11-10 The original image 147
Figure 11-11 An image with light to midrange brown colors masked out 148
Figure 11-12 A image after masking colors from dark brown to black 148
Figure 11-13 An image drawn after masking a range of colors and setting a fill color 149
Figure 11-14 A masking image 150
Figure 11-15 An image drawn to a context after clipping the content with an image mask 150
Figure 11-16 An image drawn to a context after clipping the content with an image 151

12
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
FIGURES, TABLES, AND LISTINGS

Figure 11-17 Background drawing (left) and foreground image (right) 152
Figure 11-18 Drawing an image over a background using normal blend mode 152
Figure 11-19 Drawing an image over a background using multiply blend mode 153
Figure 11-20 Drawing an image over a background using screen blend mode 154
Figure 11-21 Drawing an image over a background using overlay blend mode 154
Figure 11-22 Drawing an image over a background using darken blend mode 155
Figure 11-23 Drawing an image over a background using lighten blend mode 156
Figure 11-24 Drawing an image over a background using color dodge blend mode 156
Figure 11-25 Drawing an image over a background using color burn blend mode 157
Figure 11-26 Drawing an image over a background using soft light blend mode 158
Figure 11-27 Drawing an image over a background using hard light blend mode 158
Figure 11-28 Drawing an image over a background using difference blend mode 159
Figure 11-29 Drawing an image over a background using exclusion blend mode 160
Figure 11-30 Drawing an image over a background using hue blend mode 160
Figure 11-31 Drawing an image over a background using saturation blend mode 161
Figure 11-32 Drawing an image over a background using color blend mode 161
Figure 11-33 Drawing an image over a background using luminosity blend mode 162
Table 11-1 Functions for creating images 140
Listing 11-1 Code that creates a subimage and draws it enlarged 141
Listing 11-2 The prototype for the function CGImageMaskCreate 143
Listing 11-3 Masking light to mid-range brown colors in an image 147
Listing 11-4 Masking shades of brown to black 148
Listing 11-5 Masking a range of colors and setting a fill color and 149

Chapter 12 Core Graphics Layer Drawing 163

Figure 12-1 Repeatedly painting the same butterfly image 163


Figure 12-2 Layer drawing 164
Figure 12-3 A layer that contains two rectangles and a series of lines 166
Figure 12-4 Drawing a layer repeatedly 167
Figure 12-5 The result of using layers to draw the United States flag 167
Listing 12-1 Code that uses layers to draw a flag 168

Chapter 13 PDF Document Creation, Viewing, and Transforming 173

Figure 13-1 Quartz creates high-quality PDF documents 173


Figure 13-2 A PDF document 174
Figure 13-3 A PDF page rotated 90 degrees to the right 177
Listing 13-1 Creating a CGPDFDocument object from a PDF file 174
Listing 13-2 Drawing a PDF page 175
Listing 13-3 Creating an affine transform for a PDF page 177
Listing 13-4 Creating a PDF file 178

13
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
FIGURES, TABLES, AND LISTINGS

Chapter 14 PDF Document Parsing 181

Figure 14-1 Metadata for two images in a PDF file 182


Figure 14-2 Thumbnail images 183
Table 14-1 Marked content operators represent some of the PDF operators that you can parse
184
Listing 14-1 Getting a thumbnail view of a PDF 182
Listing 14-2 A callback for the MP operator 184
Listing 14-3 Setting callbacks for an operator table 185
Listing 14-4 Opening a PDF document from a URL 185
Listing 14-5 Scanning each page of a document 186

Chapter 15 PostScript Conversion 189

Figure 15-1 A status message for a PostScript conversion application 189


Listing 15-1 The PostScript converter callbacks data structure 190

Chapter 16 Text 193

Figure 16-1 Text drawn using Quartz 2D functions 198


Table 16-1 Text attributes and the functions that control them 194
Table 16-2 Text drawing modes 195
Listing 16-1 Drawing text 196
Listing 16-2 Drawing text using Quartz 2D in an iOS application 198

14
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
INTRODUCTION

Introduction

Quartz 2D is an advanced, two-dimensional drawing engine available for iOS application development and
to all Mac OS X application environments outside of the kernel. Quartz 2D provides low-level, lightweight
2D rendering with unmatched output fidelity regardless of display or printing device. Quartz 2D is resolution-
and device-independent; you don’t need to think about the final destination when you use the Quartz 2D
application programming interface (API) for drawing.

The Quartz 2D API is easy to use and provides access to powerful features such as transparency layers,
path-based drawing, offscreen rendering, advanced color management, anti-aliased rendering, and PDF
document creation, display, and parsing.

The Quartz 2D API is part of the Core Graphics framework, so you may see Quartz referred to as Core Graphics
or, simply, CG.

Who Should Read This Document?

This document is intended for iOS and Mac OS X developers who need to perform any of the following tasks:

● Draw graphics

● Provide graphics editing capabilities in an application

● Create or display bitmap images

● Work with PDF documents

Organization of This Document

This document is organized into the following chapters:

● “Overview of Quartz 2D” (page 19) describes the page, drawing destinations, Quartz opaque data types,
graphics states, coordinates, and memory management, and it takes a look at how Quartz works “under
the hood.”

● “Graphics Contexts” (page 29) describes the kinds of drawing destinations and provides step-by-step
instructions for creating all flavors of graphics contexts.

● “Paths” (page 43) discusses the basic elements that make up paths, shows how to create and paint them,
shows how to set up a clipping area, and explains how blend modes affect painting.

● “Color and Color Spaces” (page 67) discusses color values and using alpha values for transparency, and
it describes how to create a color space, set colors, create color objects, and set rendering intent.

Who Should Read This Document? 15


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction

● “Transforms” (page 75) describes the current transformation matrix and explains how to modify it, shows
how to set up affine transforms, shows how to convert between user and device space, and provides
background information on the mathematical operations that Quartz performs.

● “Patterns” (page 85) defines what a pattern and its parts are, tells how Quartz renders them, and shows
how to create colored and stenciled patterns.

● “Shadows” (page 101) describes what shadows are, explains how they work, and shows how to paint
with them.

● “Gradients” (page 105) discusses axial and radial gradients and shows how to create and use CGShading
and CGGradient objects.

● “Transparency Layers” (page 125) gives examples of what transparency layers look like, discusses how
they work, and provides step-by-step instructions for implementing them.

● “Data Management in Quartz 2D” (page 129) discusses how to move data into and out of Quartz.

● “Bitmap Images and Image Masks” (page 135) describes what makes up a bitmap image definition and
shows how to use a bitmap image as a Quartz drawing primitive. It also describes masking techniques
you can use on images and shows the various effects you can achieve by using blend modes when
drawing images.

● “Core Graphics Layer Drawing” (page 163) describes how to create and use drawing layers to achieve
high-performance patterned drawing or to draw offscreen.

● “PDF Document Creation, Viewing, and Transforming” (page 173) shows how to open and view PDF
documents, apply transforms to them, create a PDF file, access PDF metadata, add links, and add security
features (such as password protection).

● “PDF Document Parsing” (page 181) describes how to use CGPDFScanner and CGPDFContentStream
objects to parse and inspect PDF documents.

● “PostScript Conversion” (page 189) gives an overview of the functions you can use in Mac OS X to convert
a PostScript file to a PDF document. These functions are not available in iOS.

● “Text” (page 193) describes Quartz 2D low-level support for text and glyphs, and alternatives that provide
higher-level and Unicode text support. It also discusses how to copy font variations.

● “Glossary” (page 201) defines the terms used in this guide.

See Also

These items are essential reading for anyone using Quartz 2D:

● Quartz 2D Reference Collection, organized by header file, provides a complete reference for the Quartz
2D application programming interface.

● Color Management Overview is a brief introduction to the principles of color perception, color spaces,
and color management systems.

● Mailing lists. Join the quartz-dev mailing list to discuss problems using Quartz 2D.

16 See Also
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction

● Programming With Quartz: 2D and PDF Graphics in Mac OS X provides in-depth information on using
Quartz. This book is current through Mac OS X v10.4 and was written prior to the introduction of iOS.
The book includes examples that show how to support earlier versions of Mac OS X as well as how to
use the features introduced in v10.4. The sample code associated with this book is available from the
publisher.

See Also 17
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction

18 See Also
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 1

Overview of Quartz 2D

Quartz 2D is a two-dimensional drawing engine accessible in the iOS environment and from all Mac OS X
application environments outside of the kernel. You can use the Quartz 2D application programming interface
(API) to gain access to features such as path-based drawing, painting with transparency, shading, drawing
shadows, transparency layers, color management, anti-aliased rendering, PDF document generation, and
PDF metadata access. Whenever possible, Quartz 2D leverages the power of the graphics hardware.

In Mac OS X, Quartz 2D can work with all other graphics and imaging technologies—Core Image, Core Video,
OpenGL, and QuickTime. It’s possible to create an image in Quartz from a QuickTime graphics importer, using
the QuickTime function GraphicsImportCreateCGImage. See QuickTime Framework Reference for details.
“Moving Data Between Quartz 2D and Core Image in Mac OS X” (page 132) describes how you can provide
images to Core Image, which is a framework that supports image processing.

Similarly, in iOS, Quartz 2D works with all available graphics and animation technologies, such as Core
Animation, OpenGL ES, and the UIKit classes.

The Page

Quartz 2D uses the painter’s model for its imaging. In the painter’s model, each successive drawing operation
applies a layer of “paint” to an output “canvas,” often called a page. The paint on the page can be modified
by overlaying more paint through additional drawing operations. An object drawn on the page cannot be
modified except by overlaying more paint. This model allows you to construct extremely sophisticated images
from a small number of powerful primitives.

Figure 1-1 shows how the painter’s model works. To get the image in the top part of the figure, the shape
on the left was drawn first followed by the solid shape. The solid shape overlays the first shape, obscuring
all but the perimeter of the first shape. The shapes are drawn in the opposite order in the bottom of the
figure, with the solid shape drawn first. As you can see, in the painter’s model the drawing order is important.

The Page 19
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
Overview of Quartz 2D

Figure 1-1 The painter’s model

Drawing order Result

Result
Drawing order

The page may be a real sheet of paper (if the output device is a printer); it may be a virtual sheet of paper (if
the output device is a PDF file); it may even be a bitmap image. The exact nature of the page depends on
the particular graphics context you use.

Drawing Destinations: The Graphics Context

A graphics context is an opaque data type (CGContextRef) that encapsulates the information Quartz uses
to draw images to an output device, such as a PDF file, a bitmap, or a window on a display. The information
inside a graphics context includes graphics drawing parameters and a device-specific representation of the
paint on the page. All objects in Quartz are drawn to, or contained by, a graphics context.

You can think of a graphics context as a drawing destination, as shown in Figure 1-2. When you draw with
Quartz, all device-specific characteristics are contained within the specific type of graphics context you use.
In other words, you can draw the same image to a different device simply by providing a different graphics
context to the same sequence of Quartz drawing routines. You do not need to perform any device-specific
calculations; Quartz does it for you.

20 Drawing Destinations: The Graphics Context


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
Overview of Quartz 2D

Figure 1-2 Quartz drawing destinations

Window

Printer Layer

Drawing

PDF Bitmap

These graphics contexts are available to your application:

● A bitmap graphics context allows you to paint RGB colors, CMYK colors, or grayscale into a bitmap. A
bitmap is a rectangular array (or raster) of pixels, each pixel representing a point in an image. Bitmap
images are also called sampled images. See “Creating a Bitmap Graphics Context” (page 35).

● A PDF graphics context allows you to create a PDF file. In a PDF file, your drawing is preserved as a
sequence of commands. There are some significant differences between PDF files and bitmaps:

● PDF files, unlike bitmaps, may contain more than one page.

● When you draw a page from a PDF file on a different device, the resulting image is optimized for
the display characteristics of that device.

● PDF files are resolution independent by nature—the size at which they are drawn can be increased
or decreased infinitely without sacrificing image detail. The user-perceived quality of a bitmap image
is tied to the resolution at which the bitmap is intended to be viewed.

See “Creating a PDF Graphics Context” (page 31).

● A window graphics context is a graphics context that you can use to draw into a window. Note that
because Quartz 2D is a graphics engine and not a window management system, you use one of the
application frameworks to obtain a graphics context for a window. See “Creating a Window Graphics
Context in Mac OS X” (page 29) for details.

● A layer context (CGLayerRef) is an offscreen drawing destination associated with another graphics
context. It is designed for optimal performance when drawing the layer to the graphics context that
created it. A layer context can be a much better choice for offscreen drawing than a bitmap graphics
context. See “Core Graphics Layer Drawing” (page 163).

Drawing Destinations: The Graphics Context 21


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
Overview of Quartz 2D

● When you want to print in Mac OS X, you send your content to a PostScript graphics context that is
managed by the printing framework. See “Obtaining a Graphics Context for Printing” (page 41) for more
information.

Quartz 2D Opaque Data Types

The Quartz 2D API defines a variety of opaque data types in addition to graphics contexts. Because the API
is part of the Core Graphics framework, the data types and the routines that operate on them use the CG
prefix.

Quartz 2D creates objects from opaque data types that your application operates on to achieve a particular
drawing output. Figure 1-3 shows the sorts of results you can achieve when you apply drawing operations
to three of the objects provided by Quartz 2D. For example:

● You can rotate and display a PDF page by creating a PDF page object, applying a rotation operation to
the graphics context, and asking Quartz 2D to draw the page to a graphics context.

● You can draw a pattern by creating a pattern object, defining the shape that makes up the pattern, and
setting up Quartz 2D to use the pattern as paint when it draws to a graphics context.

● You can fill an area with an axial or radial shading by creating a shading object, providing a function
that determines the color at each point in the shading, and then asking Quartz 2D to use the shading
as a fill color.

Figure 1-3 Opaque data types are the basis of drawing primitives in Quartz 2D

PDF pages Patterns Shading

The opaque data types available in Quartz 2D include the following:

● CGPathRef, used for vector graphics to create paths that you fill or stroke. See “Paths” (page 43).

● CGImageRef, used to represent bitmap images and bitmap image masks based on sample data that
you supply. See “Bitmap Images and Image Masks” (page 135).

● CGLayerRef, used to represent a drawing layer that can be used for repeated drawing (such as for
backgrounds or patterns) and for offscreen drawing. See “Core Graphics Layer Drawing” (page 163)

● CGPatternRef, used for repeated drawing. See “Patterns” (page 85).

22 Quartz 2D Opaque Data Types


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
Overview of Quartz 2D

● CGShadingRef and CGGradientRef, used to paint gradients. See “Gradients” (page 105).

● CGFunctionRef, used to define callback functions that take an arbitrary number of floating-point
arguments. You use this data type when you create gradients for a shading. See “Gradients” (page 105).

● CGColorRef and CGColorSpaceRef, used to inform Quartz how to interpret color. See “Color and
Color Spaces” (page 67).

● CGImageSourceRef and CGImageDestinationRef, which you use to move data into and out of
Quartz. See “Data Management in Quartz 2D” (page 129) and Image I/O Programming Guide.

● CGFontRef, used to draw text. See “Text” (page 193).

● CGPDFDictionaryRef, CGPDFObjectRef, CGPDFPageRef, CGPDFStream, CGPDFStringRef, and


CGPDFArrayRef, which provide access to PDF metadata. See “PDF Document Creation, Viewing, and
Transforming” (page 173).

● CGPDFScannerRef and CGPDFContentStreamRef, which parse PDF metadata. See “PDF Document
Parsing” (page 181).

● CGPSConverterRef, used to convert PostScript to PDF. It is not available in iOS. See “PostScript
Conversion” (page 189).

Graphics States

Quartz modifies the results of drawing operations according to the parameters in the current graphics state.
The graphics state contains parameters that would otherwise be taken as arguments to drawing routines.
Routines that draw to a graphics context consult the graphics state to determine how to render their results.
For example, when you call a function to set the fill color, you are modifying a value stored in the current
graphics state. Other commonly used elements of the current graphics state include the line width, the
current position, and the text font size.

The graphics context contains a stack of graphics states. When Quartz creates a graphics context, the stack
is empty. When you save the graphics state, Quartz pushes a copy of the current graphics state onto the
stack. When you restore the graphics state, Quartz pops the graphics state off the top of the stack. The popped
state becomes the current graphics state.

To save the current graphics state, use the function CGContextSaveGState to push a copy of the current
graphics state onto the stack. To restore a previously saved graphics state, use the function
CGContextRestoreGState to replace the current graphics state with the graphics state that’s on top of
the stack.

Note that not all aspects of the current drawing environment are elements of the graphics state. For example,
the current path is not considered part of the graphics state and is therefore not saved when you call the
function CGContextSaveGState. The graphics state parameters that are saved when you call this function
are listed in Table 1-1.

Graphics States 23
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
Overview of Quartz 2D

Table 1-1 Parameters that are associated with the graphics state

Parameters Discussed in this chapter

Current transformation matrix (CTM) “Transforms” (page 75)

Clipping area “Paths” (page 43)

Line: width, join, cap, dash, miter limit “Paths” (page 43)

Accuracy of curve estimation (flatness) “Paths” (page 43)

Anti-aliasing setting “Graphics Contexts” (page 29)

Color: fill and stroke settings “Color and Color Spaces” (page 67)

Alpha value (transparency) “Color and Color Spaces” (page 67)

Rendering intent “Color and Color Spaces” (page 67)

Color space: fill and stroke settings “Color and Color Spaces” (page 67)

Text: font, font size, character spacing, text drawing “Text” (page 193)
mode

Blend mode “Paths” (page 43) and “Bitmap Images and Image
Masks” (page 135)

Quartz 2D Coordinate Systems

A coordinate system, shown in Figure 1-4, defines the range of locations used to express the location and
sizes of objects to be drawn on the page. You specify the location and size of graphics in the user-space
coordinate system, or, more simply, the user space. Coordinates are defined as floating-point values.

Figure 1-4 The Quartz coordinate system

y-axis

(0,0) x-axis

Because different devices have different underlying imaging capabilities, the locations and sizes of graphics
must be defined in a device-independent manner. For example, a screen display device might be capable
of displaying no more than 96 pixels per inch, while a printer might be capable of displaying 300 pixels per

24 Quartz 2D Coordinate Systems


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
Overview of Quartz 2D

inch. If you define the coordinate system at the device level (in this example, either 96 pixels or 300 pixels),
objects drawn in that space cannot be reproduced on other devices without visible distortion. They will
appear too large or too small.

Quartz accomplishes device independence with a separate coordinate system—user space—mapping it to


the coordinate system of the output device—device space—using the current transformation matrix, or
CTM. A matrix is a mathematical construct used to efficiently describe a set of related equations. The current
transformation matrix is a particular type of matrix called an affine transform, which maps points from one
coordinate space to another by applying translation, rotation, and scaling operations (calculations that
move, rotate, and resize a coordinate system).

The current transformation matrix has a secondary purpose: It allows you to transform how objects are drawn.
For example, to draw a box rotated by 45 degrees, you rotate the coordinate system of the page (the CTM)
before you draw the box. Quartz draws to the output device using the rotated coordinate system.

A point in user space is represented by a coordinate pair (x,y), where x represents the location along the
horizontal axis (left and right) and y represents the vertical axis (up and down). The origin of the user
coordinate space is the point (0,0). The origin is located at the lower-left corner of the page, as shown in
Figure 1-4 (page 24). In the default coordinate system for Quartz, the x-axis increases as it moves from the
left toward the right of the page. The y-axis increases in value as it moves from the bottom toward the top
of the page.

Some technologies set up their graphics contexts using a different default coordinate system than the one
used by Quartz. Relative to Quartz, such a coordinate system is a modified coordinate system and must be
compensated for when performing some Quartz drawing operations. The most common modified coordinate
system places the origin in the upper-right corner of the context and changes the y-axis to point towards
the bottom of the page. A few places where you might see this specific coordinate system used are the
following:

● In Mac OS X, a subclass of NSView that overrides its isFlipped method to return YES.

● In iOS, a drawing context returned by an UIView.

● In iOS, a drawing context created by calling the UIGraphicsBeginImageContextWithOptions


function.

The reason UIKit returns Quartz drawing contexts with modified coordinate systems is that UIKit uses a
different default coordinate convention; it applies the transform to Quartz contexts it creates so that they
match its conventions. If your application wants to use the same drawing routines to draw to both a UIView
object and a PDF graphics context (which is created by Quartz and uses the default coordinate system), you
need to apply a transform so that the PDF graphics context receives the same modified coordinate system.
To do this, apply a transform that translates the origin to the upper-left corner of the PDF context and scales
the y-coordinate by -1.

Using a scaling transform to negate the y-coordinate alters some conventions in Quartz drawing. For example,
if you call CGContextDrawImage to draw an image into the context, the image is modified by the transform
when it is drawn into the destination. Similarly, path drawing routines accept parameters that specify whether
an arc is drawn in a clockwise or counterclockwise direction in the default coordinate system. If a coordinate
system is modified, the result is also modified, as if the image were reflected in a mirror. In Figure 1-5, passing
the same parameters into Quartz results in a clockwise arc in the default coordinate system and a
counterclockwise arc after the y-coordinate is negated by the transform.

Quartz 2D Coordinate Systems 25


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
Overview of Quartz 2D

Figure 1-5 Modifying the coordinate system creates a mirrored image.

y (0,0)
x

(0,0)
x
y
Default Coordinates Modified Coordinates

flipped_coordinates.eps
Cocoa Drawing
Apple Computer, Inc.
February 9, 2006

It is up to your application to adjust any Quartz calls it makes to a context that has a transform applied to it.
For example, if you want an image or PDF to draw correctly into a graphics context, your application may
need to temporarily adjust the CTM of the graphics context. In iOS, if you use a UIImage object to wrap a
CGImage object you create, you do not need to modify the CTM. The UIImage object automatically
compensates for the modified coordinate system applied by UIKit.

Important: The above discussion is essential to understand if you plan to write applications that directly
target Quartz on iOS, but it is not sufficient. On iOS 3.2 and later, when UIKit creates a drawing context for
your application, it also makes additional changes to the context to match the default UIKIt conventions. In
particular, patterns and shadows, which are not affected by the CTM, are adjusted separately so that their
conventions match UIKit’s coordinate system. In this case, there is no equivalent mechanism to the CTM that
your application can use to change a context created by Quartz to match the behavior for a context provided
by UIKit; your application must recognize the what kind of context it is drawing into and adjust its behavior
to match the expectations of the context.

Memory Management: Object Ownership

Quartz uses the Core Foundation memory management model, in which objects are reference counted.
When created, Core Foundation objects start out with a reference count of 1. You can increment the reference
count by calling a function to retain the object, and decrement the reference count by calling a function to
release the object. When the reference count is decremented to 0, the object is freed. This model allows
objects to safely share references to other objects.

26 Memory Management: Object Ownership


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
Overview of Quartz 2D

There are a few simple rules to keep in mind:

● If you create or copy an object, you own it, and therefore you must release it. That is, in general, if you
obtain an object from a function with the words “Create” or “Copy” in its name, you must release the
object when you’re done with it. Otherwise, a memory leak results.

● If you obtain an object from a function that does not contain the words “Create” or “Copy” in its name,
you do not own a reference to the object, and you must not release it. The object will be released by its
owner at some point in the future.

● If you do not own an object and you need to keep it around, you must retain it and release it when
you’re done with it. You use the Quartz 2D functions specific to an object to retain and release that
object. For example, if you create a CGColorspace object, you use the functions CGColorSpaceRetain
and CGColorSpaceRelease to retain and release the object as needed. You can also use the Core
Foundation functions CFRetain and CFRelease, but you must be careful not to pass NULL to these
functions.

Memory Management: Object Ownership 27


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
Overview of Quartz 2D

28 Memory Management: Object Ownership


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2

Graphics Contexts

A graphics context represents a drawing destination. It contains drawing parameters and all device-specific
information that the drawing system needs to perform any subsequent drawing commands. A graphics
context defines basic drawing attributes such as the colors to use when drawing, the clipping area, line width
and style information, font information, compositing options, and several others.

You can obtain a graphics context by using Quartz context creation functions or by using higher-level functions
provided by one of the Mac OS X frameworks or the UIKit framework in iOS. Quartz provides functions for
various flavors of Quartz graphics contexts including bitmap and PDF, which you can use to create custom
content.

This chapter shows you how to create a graphics context for a variety of drawing destinations. A graphics
context is represented in your code by the data type CGContextRef, which is an opaque data type. After
you obtain a graphics context, you can use Quartz 2D functions to draw to the context, perform operations
(such as translations) on the context, and change graphics state parameters, such as line width and fill color.

Drawing to a View Graphics Context in iOS

To draw to the screen in an iOS application, you set up a UIView object and implement its drawRect:
method to perform drawing. The view’s drawRect: method is called when the view is visible onscreen and
its contents need updating. Before calling your custom drawRect: method, the view object automatically
configures its drawing environment so that your code can start drawing immediately. As part of this
configuration, the UIView object creates a graphics context (a CGContextRef opaque type) for the current
drawing environment. You obtain this graphics context in your drawRect: method by calling the UIKit
function UIGraphicsGetCurrentContext.

The default coordinate system used throughout UIKit is different from the coordinate system used by Quartz.
In UIKit, the origin is in the upper-left corner, with the positive-y value pointing downward. The UIView
object modifies the CTM of the Quartz graphics context to match the UIKit conventions by translating the
origin to the upper left corner of the view and inverting the y-axis by multiplying it by -1. For more information
on modified-coordinate systems and the implications in your own drawing code, see “Quartz 2D
Coordinates” (page 24).

UIView objects are described in detail in View Programming Guide for iOS.

Creating a Window Graphics Context in Mac OS X

When drawing in Mac OS X, you need to create a window graphics context that’s appropriate for the framework
you are using. The Quartz 2D API itself provides no functions to obtain a windows graphics context. Instead,
you use the Cocoa framework to obtain a context for a window created in Cocoa.

Drawing to a View Graphics Context in iOS 29


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

You obtain a Quartz graphics context from within the drawRect: routine of a Cocoa application using the
following line of code:

CGContextRef myContext = [[NSGraphicsContext currentContext] graphicsPort];

The method currentContext returns the NSGraphicsContext instance of the current thread. The method
graphicsPort returns the low-level, platform-specific graphics context represented by the receiver, which
is a Quartz graphics context. (Don’t get confused by the method names; they are historical.) For more
information see NSGraphicsContext Class Reference.

After you obtain the graphics context, you can call any of the Quartz 2D drawing functions in your Cocoa
application. You can also mix Quartz 2D calls with Cocoa drawing calls. You can see an example of Quartz
2D drawing to a Cocoa view by looking at Figure 2-1. The drawing consists of two overlapping rectangles,
an opaque red one and a partially transparent blue one. You’ll learn more about transparency in “Color and
Color Spaces” (page 67). The ability to control how much you can “see through” colors is one of the hallmark
features of Quartz 2D.

Figure 2-1 A view in the Cocoa framework that contains Quartz drawing

To create the drawing in Figure 2-1, you first create a Cocoa application Xcode project. In Interface Builder,
drag a Custom View to the window and subclass it. Then write an implementation for the subclassed view,
similar to what Listing 2-1 shows. For this example, the subclassed view is named MyQuartzView. The
drawRect: method for the view contains all the Quartz drawing code. A detailed explanation for each
numbered line of code appears following the listing.

Note: The drawRect: method of the NSView class is invoked automatically each time the view needs to be
drawn. To find out more about overriding the drawRect: method, see NSView Class Reference.

Listing 2-1 Drawing to a window graphics context


@implementation MyQuartzView

- (id)initWithFrame:(NSRect)frameRect
{

30 Creating a Window Graphics Context in Mac OS X


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

self = [super initWithFrame:frameRect];


return self;
}

- (void)drawRect:(NSRect)rect
{
CGContextRef myContext = [[NSGraphicsContext // 1
currentContext] graphicsPort];
// ********** Your drawing code here ********** // 2
CGContextSetRGBFillColor (myContext, 1, 0, 0, 1); // 3
CGContextFillRect (myContext, CGRectMake (0, 0, 200, 100 )); // 4
CGContextSetRGBFillColor (myContext, 0, 0, 1, .5); // 5
CGContextFillRect (myContext, CGRectMake (0, 0, 100, 200)); // 6
}

@end

Here’s what the code does:

1. Obtains a graphics context for the view.

2. This is where you insert your drawing code. The four lines of code that follow are examples of using
Quartz 2D functions.

3. Sets a red fill color that’s fully opaque. For information on colors and alpha (which sets opacity), see
“Color and Color Spaces” (page 67).

4. Fills a rectangle whose origin is (0,0) and whose width is 200 and height is 100. For information on
drawing rectangles, see “Paths” (page 43).

5. Sets a blue fill color that’s partially transparent.

6. Fills a rectangle whose origin is (0,0) and whose width is 100 and height is 200.

Creating a PDF Graphics Context

When you create a PDF graphics context and draw to that context, Quartz records your drawing as a series
of PDF drawing commands written to a file. You supply a location for the PDF output and a default media
box—a rectangle that specifies bounds of the page. Figure 2-2 shows the result of drawing to a PDF graphics
context and then opening the resulting PDF in Preview.

Creating a PDF Graphics Context 31


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

Figure 2-2 A PDF created by using CGPDFContextCreateWithURL

The Quartz 2D API provides two functions that create a PDF graphics context:

● CGPDFContextCreateWithURL, which you use when you want to specify the location for the PDF
output as a Core Foundation URL. Listing 2-2 (page 32) shows how to use this function to create a PDF
graphics context.

● CGPDFContextCreate, which you use when you want the PDF output sent to a data consumer. (For
more information see “Data Management in Quartz 2D” (page 129).) Listing 2-3 (page 33) shows how to
use this function to create a PDF graphics context.

A detailed explanation for each numbered line of code follows each listing.

iOS Note: A PDF graphics context in iOS uses the default coordinate system provided by Quartz, without
applying a transform to match the UIKit coordinate system. If your application plans on sharing drawing
code between your PDF graphics context and the graphics context provided by UIView object, your application
should modify the CTM of the PDF graphics context to modify the coordinate system. See “Quartz 2D
Coordinates” (page 24).

Listing 2-2 Calling CGPDFContextCreateWithURL to create a PDF graphics context


CGContextRef MyPDFContextCreate (const CGRect *inMediaBox,
CFStringRef path)
{
CGContextRef myOutContext = NULL;
CFURLRef url;

32 Creating a PDF Graphics Context


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

url = CFURLCreateWithFileSystemPath (NULL, // 1


path,
kCFURLPOSIXPathStyle,
false);
if (url != NULL) {
myOutContext = CGPDFContextCreateWithURL (url, // 2
inMediaBox,
NULL);
CFRelease(url); // 3
}
return myOutContext; // 4
}

Here’s what the code does:

1. Calls the Core Foundation function to create a CFURL object from the CFString object supplied to the
MyPDFContextCreate function. You pass NULL as the first parameter to use the default allocator. You
also need to specify a path style, which for this example is a POSIX-style pathname.

2. Calls the Quartz 2D function to create a PDF graphics context using the PDF location just created (as a
CFURL object) and a rectangle that specifies the bounds of the PDF. The rectangle (CGRect) was passed
to the MyPDFContextCreate function and is the default page media bounding box for the PDF.

3. Releases the CFURL object.

4. Returns the PDF graphics context. The caller must release the graphics context when it is no longer
needed.

Listing 2-3 Calling CGPDFContextCreate to create a PDF graphics context


CGContextRef MyPDFContextCreate (const CGRect *inMediaBox,
CFStringRef path)
{
CGContextRef myOutContext = NULL;
CFURLRef url;
CGDataConsumerRef dataConsumer;

url = CFURLCreateWithFileSystemPath (NULL, // 1


path,
kCFURLPOSIXPathStyle,
false);

if (url != NULL)
{
dataConsumer = CGDataConsumerCreateWithURL (url); // 2
if (dataConsumer != NULL)
{
myOutContext = CGPDFContextCreate (dataConsumer, // 3
inMediaBox,
NULL);
CGDataConsumerRelease (dataConsumer); // 4
}
CFRelease(url); // 5
}
return myOutContext; // 6
}

Creating a PDF Graphics Context 33


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

Here’s what the code does:

1. Calls the Core Foundation function to create a CFURL object from the CFString object supplied to the
MyPDFContextCreate function. You pass NULL as the first parameter to use the default allocator. You
also need to specify a path style, which for this example is a POSIX-style pathname.

2. Creates a Quartz data consumer object using the CFURL object. If you don’t want to use a CFURL object
(for example, you want to place the PDF data in a location that can’t be specified by a CFURL object),
you can instead create a data consumer from a set of callback functions that you implement in your
application. For more information, see “Data Management in Quartz 2D” (page 129).

3. Calls the Quartz 2D function to create a PDF graphics context passing as parameters the data consumer
and the rectangle (of type CGRect) that was passed to the MyPDFContextCreate function. This rectangle
is the default page media bounding box for the PDF.

4. Releases the data consumer.

5. Releases the CFURL object.

6. Returns the PDF graphics context. The caller must release the graphics context when it is no longer
needed.

Listing 2-4 shows how to call the MyPDFContextCreate routine and draw to it. A detailed explanation for
each numbered line of code appears following the listing.

Listing 2-4 Drawing to a PDF graphics context


CGRect mediaBox; // 1

mediaBox = CGRectMake (0, 0, myPageWidth, myPageHeight); // 2


myPDFContext = MyPDFContextCreate (&mediaBox, CFSTR("test.pdf")); // 3

CFStringRef myKeys[1]; // 4
CFTypeRef myValues[1];
myKeys[0] = kCGPDFContextMediaBox;
myValues[0] = (CFTypeRef) CFDataCreate(NULL,(const UInt8 *)&mediaBox, sizeof
(CGRect));
CFDictionaryRef pageDictionary = CFDictionaryCreate(NULL, (const void **)
myKeys,
(const void **) myValues,
1,

&kCFTypeDictionaryKeyCallBacks,
&
kCFTypeDictionaryValueCallBacks);
CGPDFContextBeginPage(myPDFContext, &pageDictionary); // 5
// ********** Your drawing code here ********** // 6
CGContextSetRGBFillColor (myPDFContext, 1, 0, 0, 1);
CGContextFillRect (myPDFContext, CGRectMake (0, 0, 200, 100 ));
CGContextSetRGBFillColor (myPDFContext, 0, 0, 1, .5);
CGContextFillRect (myPDFContext, CGRectMake (0, 0, 100, 200 ));
CGPDFContextEndPage(myPDFContext); // 7
CFRelease(pageDictionary); // 8
CFRelease(myValues[0]);
CGContextRelease(myPDFContext);

34 Creating a PDF Graphics Context


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

Here’s what the code does:

1. Declares a variable for the rectangle that you use to define the PDF media box.

2. Sets the origin of the media box to (0,0) and the width and height to variables supplied by the
application.

3. Calls the function MyPDFContextCreate (See Listing 2-3 (page 33)) to obtain a PDF graphics context,
supplying a media box and a pathname. The macro CFSTR converts a string to a CFStringRef data
type.

4. Sets up a dictionary with the page options. In this example, only the media box is specified. You don’t
have to pass the same rectangle you used to set up the PDF graphics context. The media box you add
here supersedes the rectangle you pass to set up the PDF graphics context.

5. Signals the start of a page. This function is used for page-oriented graphics, which is what PDF drawing
is.

6. Calls Quartz 2D drawing functions. You replace this and the following four lines of code with the drawing
code appropriate for your application.

7. Signals the end of the PDF page.

8. Releases the dictionary and the PDF graphics context when they are no longer needed.

You can write any content to a PDF that’s appropriate for your application—images, text, path drawing—and
you can add links and encryption. For more information see “PDF Document Creation, Viewing, and
Transforming” (page 173).

Creating a Bitmap Graphics Context

A bitmap graphics context accepts a pointer to a memory buffer that contains storage space for the bitmap.
When you paint into the bitmap graphics context, the buffer is updated. After you release the graphics
context, you have a fully updated bitmap in the pixel format you specify.

Creating a Bitmap Graphics Context 35


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

Note: Bitmap graphics contexts are sometimes used for drawing offscreen. Before you decide to use a bitmap
graphics context for this purpose, see “Core Graphics Layer Drawing” (page 163). CGLayer objects (CGLayerRef)
are optimized for offscreen drawing because, whenever possible, Quartz caches layers on the video card.

iOS Note: iOS applications should use the function UIGraphicsBeginImageContextWithOptions instead
of using the low-level Quartz functions described here. If your application creates an offscreen bitmap using
Quartz, the coordinate system used by bitmap graphics context is the default Quartz coordinate system. In
contrast, if your application creates an image context by calling the function
UIGraphicsBeginImageContextWithOptions, UIKit applies the same transformation to the context’s
coordinate system as it does to a UIView object’s graphics context. This allows your application to use the
same drawing code for either without having to worry about different coordinate systems. Although your
application can manually adjust the coordinate transformation matrix to achieve the correct results, in practice,
there is no performance benefit to doing so.

You use the function CGBitmapContextCreate to create a bitmap graphics context. This function takes
the following parameters:

● data. Supply a pointer to the destination in memory where you want the drawing rendered. The size
of this memory block should be at least (bytesPerRow*height) bytes.

● width. Specify the width, in pixels, of the bitmap.

● height. Specify the height, in pixels, of the bitmap.

● bitsPerComponent. Specify the number of bits to use for each component of a pixel in memory. For
example, for a 32-bit pixel format and an RGB color space, you would specify a value of 8 bits per
component. See “Supported Pixel Formats” (page 39).

● bytesPerRow. Specify the number of bytes of memory to use per row of the bitmap.

Tip: When you create a bitmap graphics context, you’ll get the best performance if you make sure the
data and bytesPerRow are 16-byte aligned.

● colorspace. The color space to use for the bitmap context. You can provide a Gray, RGB, CMYK, or
NULL color space when you create a bitmap graphics context. For detailed information on color spaces
and color management principles, see Color Management Overview. For information on creating and
using color spaces in Quartz, see “Color and Color Spaces” (page 67). For information about supported
color spaces, see “Color Spaces and Bitmap Layout” (page 137) in the “Bitmap Images and Image
Masks” (page 135) chapter.

● bitmapInfo. Bitmap layout information, expressed as a CGBitmapInfo constant, that specifies whether
the bitmap should contain an alpha component, the relative location of the alpha component (if there
is one) in a pixel, whether the alpha component is premultiplied, and whether the color components
are integer or floating-point values. For detailed information on what these constants are, when each is
used, and Quartz-supported pixel formats for bitmap graphics contexts and images, see “Color Spaces
and Bitmap Layout” (page 137) in the “Bitmap Images and Image Masks” (page 135) chapter.

Listing 2-5 shows how to create a bitmap graphics context. When you draw into the resulting bitmap graphics
context, Quartz records your drawing as bitmap data in the specified block of memory. A detailed explanation
for each numbered line of code follows the listing.

36 Creating a Bitmap Graphics Context


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

Listing 2-5 Creating a bitmap graphics context


CGContextRef MyCreateBitmapContext (int pixelsWide,
int pixelsHigh)
{
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;

bitmapBytesPerRow = (pixelsWide * 4); // 1


bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);

colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); // 2
bitmapData = calloc( bitmapByteCount ); // 3
if (bitmapData == NULL)
{
fprintf (stderr, "Memory not allocated!");
return NULL;
}
context = CGBitmapContextCreate (bitmapData, // 4
pixelsWide,
pixelsHigh,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
if (context== NULL)
{
free (bitmapData); // 5
fprintf (stderr, "Context not created!");
return NULL;
}
CGColorSpaceRelease( colorSpace ); // 6

return context; // 7
}

Here’s what the code does:

1. Declares a variable to represent the number of bytes per row. Each pixel in the bitmap in this example
is represented by 4 bytes; 8 bits each of red, green, blue, and alpha.

2. Creates a generic RGB color space. You can also create a CMYK color space. See “Color and Color
Spaces” (page 67) for more information and for a discussion of generic color spaces versus device
dependent ones.

3. Calls the calloc function to create and clear a block of memory in which to store the bitmap data. This
example creates a 32-bit RGBA bitmap (that is, an array with 32 bits per pixel, each pixel containing 8
bits each of red, green, blue, and alpha information). Each pixel in the bitmap occupies 4 bytes of memory.
In Mac OS X 10.6 and iOS 4, this step can be omitted—if you pass NULL as bitmap data, Quartz
automatically allocates space for the bitmap.

4. Creates a bitmap graphics context, supplying the bitmap data, the width and height of the bitmap, the
number of bits per component, the bytes per row, the color space, and a constant that specifies whether
the bitmap should contain an alpha channel and its relative location in a pixel. The constant

Creating a Bitmap Graphics Context 37


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

kCGImageAlphaPremultipliedLast indicates that the alpha component is stored in the last byte of
each pixel and that the color components have already been multiplied by this alpha value. See “The
Alpha Value” (page 68) for more information on premultiplied alpha.

5. If the context isn’t created for some reason, frees the memory allocated for the bitmap data.

6. Releases the color space.

7. Returns the bitmap graphics context. The caller must release the graphics context when it is no longer
needed.

Listing 2-6 shows code that calls MyCreateBitmapContext to create a bitmap graphics context, uses the
bitmap graphics context to create a CGImage object, then draws the resulting image to a window graphics
context. Figure 2-3 (page 39) shows the image drawn to the window. A detailed explanation for each
numbered line of code follows the listing.

Listing 2-6 Drawing to a bitmap graphics context


CGRect myBoundingBox; // 1

myBoundingBox = CGRectMake (0, 0, myWidth, myHeight); // 2


myBitmapContext = MyCreateBitmapContext (400, 300); // 3
// ********** Your drawing code here ********** // 4
CGContextSetRGBFillColor (myBitmapContext, 1, 0, 0, 1);
CGContextFillRect (myBitmapContext, CGRectMake (0, 0, 200, 100 ));
CGContextSetRGBFillColor (myBitmapContext, 0, 0, 1, .5);
CGContextFillRect (myBitmapContext, CGRectMake (0, 0, 100, 200 ));
myImage = CGBitmapContextCreateImage (myBitmapContext); // 5
CGContextDrawImage(myContext, myBoundingBox, myImage); // 6
char *bitmapData = CGBitmapContextGetData(myBitmapContext); // 7
CGContextRelease (myBitmapContext); // 8
if (bitmapData) free(bitmapData); // 9
CGImageRelease(myImage); // 10

Here’s what the code does:

1. Declares a variable to store the origin and dimensions of the bounding box into which Quartz will draw
an image created from the bitmap graphics context.

2. Sets the origin of the bounding box to (0,0) and the width and height to variables previously declared,
but whose declaration are not shown in this code.

3. Calls the application-supplied function MyCreateBitmapContext (see Listing 2-5 (page 37)) to create
a bitmap context that is 400 pixels wide and 300 pixels high. You can create a bitmap graphics context
using any dimensions that are appropriate for your application.

4. Calls Quartz 2D functions to draw into the bitmap graphics context. You would replace this and the next
four lines of code with drawing code appropriate for your application.

5. Creates a Quartz 2D image (CGImageRef) from the bitmap graphics context.

6. Draws the image into the location in the window graphics context that is specified by the bounding
box. The bounding box specifies the location and dimensions in user space in which to draw the image.

38 Creating a Bitmap Graphics Context


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

This example does not show the creation of the window graphics context. See “Creating a Window
Graphics Context in Mac OS X” (page 29) for information on how to create one.

7. Gets the bitmap data associated with the bitmap graphics context.

8. Releases the bitmap graphics context when it is no longer needed.

9. Free the bitmap data if it exists.

10. Releases the image when it is no longer needed.

Figure 2-3 An image created from a bitmap graphics context and drawn to a window graphics context

Supported Pixel Formats


Table 2-1 summarizes the pixel formats that are supported for bitmap graphics context, the associated color
space (cs), and the version of Mac OS X in which the format was first available. The pixel format is specified
as bits per pixel (bpp) and bits per component (bpc). The table also includes the bitmap information constant
associated with that pixel format. See CGImage Reference for details on what each of the bitmap information
format constants represent.

Table 2-1 Pixel formats supported for bitmap graphics contexts

CS Pixel format and bitmap information constant Availability

Null 8 bpp, 8 bpc, kCGImageAlphaOnly Mac OS X, iOS

Gray 8 bpp, 8 bpc,kCGImageAlphaNone Mac OS X, iOS

Gray 8 bpp, 8 bpc,kCGImageAlphaOnly Mac OS X, iOS

Gray 16 bpp, 16 bpc, kCGImageAlphaNone Mac OS X

Creating a Bitmap Graphics Context 39


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

CS Pixel format and bitmap information constant Availability

Gray 32 bpp, 32 bpc, kCGImageAlphaNone|kCGBitmapFloatComponents Mac OS X

RGB 16 bpp, 5 bpc, kCGImageAlphaNoneSkipFirst Mac OS X, iOS

RGB 32 bpp, 8 bpc, kCGImageAlphaNoneSkipFirst Mac OS X, iOS

RGB 32 bpp, 8 bpc, kCGImageAlphaNoneSkipLast Mac OS X, iOS

RGB 32 bpp, 8 bpc, kCGImageAlphaPremultipliedFirst Mac OS X, iOS

RGB 32 bpp, 8 bpc, kCGImageAlphaPremultipliedLast Mac OS X, iOS

RGB 64 bpp, 16 bpc, kCGImageAlphaPremultipliedLast Mac OS X

RGB 64 bpp, 16 bpc, kCGImageAlphaNoneSkipLast Mac OS X

RGB 128 bpp, 32 bpc, kCGImageAlphaNoneSkipLast |kCGBitmapFloatComponents Mac OS X

RGB 128 bpp, 32 bpc, kCGImageAlphaPremultipliedLast |kCGBitmapFloat- Mac OS X


Components

CMYK 32 bpp, 8 bpc, kCGImageAlphaNone Mac OS X

CMYK 64 bpp, 16 bpc, kCGImageAlphaNone Mac OS X

CMYK 128 bpp, 32 bpc, kCGImageAlphaNone |kCGBitmapFloatComponents Mac OS X

Anti-Aliasing
Bitmap graphics contexts support anti-aliasing, which is the process of artificially correcting the jagged (or
aliased) edges you sometimes see in bitmap images when text or shapes are drawn. These jagged edges
occur when the resolution of the bitmap is significantly lower than the resolution of your eyes. To make
objects appear smooth in the bitmap, Quartz uses different colors for the pixels that surround the outline of
the shape. By blending the colors in this way, the shape appears smooth. You can see the effect of using
anti-aliasing in Figure 2-4. You can turn anti-aliasing off for a particular bitmap graphics context by calling
the function CGContextSetShouldAntialias. The anti-aliasing setting is part of the graphics state.

You can control whether to allow anti-aliasing for a particular graphics context by using the function
CGContextSetAllowsAntialiasing. Pass true to this function to allow anti-aliasing; false not to allow
it. This setting is not part of the graphics state. Quartz performs anti-aliasing when the context and the graphic
state settings are set to true.

40 Creating a Bitmap Graphics Context


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

Figure 2-4 A comparison of aliased and anti-aliasing drawing

Obtaining a Graphics Context for Printing

Cocoa applications in Mac OS X implement printing through custom NSView subclasses. A view is told to
print by invoking its print: method. The view then creates a graphics context that targets a printer and
calls its drawRect: method. Your application uses the same drawing code to draw to the printer that it uses
to draw to the screen. It can also customize the drawRect: call to an image to the printer that is different
from the one sent to the screen.

For a detailed discussion of printing in Cocoa, see Printing Programming Topics for Cocoa.

Obtaining a Graphics Context for Printing 41


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 2
Graphics Contexts

42 Obtaining a Graphics Context for Printing


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 3

Paths

A path defines one or more shapes, or subpaths. A subpath can consist of straight lines, curves, or both. It
can be open or closed. A subpath can be a simple shape, such as a line, circle, rectangle, or star, or a more
complex shape such as the silhouette of a mountain range or an abstract doodle. Figure 3-1 shows some of
the paths you can create. The straight line (at the upper left of the figure) is dashed; lines can also be solid.
The squiggly path (in the middle top) is made up of several curves and is an open path. The concentric circles
are filled, but not stroked. The State of California is a closed path, made up of many curves and lines, and the
path is both stroked and filled. The stars illustrate two options for filling paths, which you’ll read about later
in this chapter.

Figure 3-1 Quartz supports path-based drawing

In this chapter, you’ll learn about the building blocks that make up paths, how to stroke and paint paths,
and the parameters that affect the appearance of paths.

Path Creation and Path Painting

Path creation and path painting are separate tasks. First you create a path. When you want to render a path,
you request Quartz to paint it. As you can see in Figure 3-1, you can choose to stroke the path, fill the path,
or both stroke and fill the path. You can also use a path to constrain the drawing of other objects within the
bounds of the path creating, in effect, a clipping area.

Figure 3-2 shows a path that has been painted and that contains two subpaths. The subpath on the left is a
rectangle, and the subpath on the right is an abstract shape made up of straight lines and curves. Each
subpath is filled and its outline stroked.

Path Creation and Path Painting 43


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 3
Paths

Figure 3-2 A path that contains two shapes, or subpaths

Figure 3-3 shows multiple paths drawn independently. Each path contains a randomly generated curve,
some of which are filled and others stroked. Drawing is constrained to a circular area by a clipping area.

Figure 3-3 A clipping area constrains drawing

The Building Blocks

Subpaths are built from lines, arcs, and curves. Quartz also provides convenience functions to add rectangles
and ellipses with a single function call. Points are also essential building blocks of paths because points define
starting and ending locations of shapes.

44 The Building Blocks


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 3
Paths

Points
Points are x and y coordinates that specify a location in user space. You can call the function
CGContextMoveToPoint to specify a starting position for a new subpath. Quartz keeps track of the current
point, which is the last location used for path construction. For example, if you call the function
CGContextMoveToPoint to set a location at (10,10), that moves the current point to (10,10). If you then
draw a horizontal line 50 units long, the last point on the line, that is, (60,10), becomes the current point.
Lines, arcs, and curves are always drawn starting from the current point.

Most of the time you specify a point by passing to Quartz functions two floating-point values to specify x
and y coordinates. Some functions require that you pass a CGPoint data structure, which holds two
floating-point values.

Lines
A line is defined by its endpoints. Its starting point is always assumed to be the current point, so when you
create a line, you specify only its endpoint. You use the function CGContextAddLineToPoint to append a
single line to a subpath.

You can add a series of connected lines to a path by calling the function CGContextAddLines. You pass
this function an array of points. The first point must be the starting point of the first line; the remaining points
are endpoints. Quartz begins a new subpath at the first point and connects a straight line segment to each
endpoint.

Arcs
Arcs are circle segments. Quartz provides two functions that create arcs. The function CGContextAddArc
creates a curved segment from a circle. You specify the center of the circle, the radius, and the radial angle
(in radians). You can create a full circle by specifying a radial angle of 2 pi. Figure 3-4 shows multiple paths
drawn independently. Each path contains a randomly generated circle; some are filled and others are stroked.

The Building Blocks 45


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 3
Paths

Figure 3-4 Multiple paths; each path contains a randomly generated circle

The function CGContextAddArcToPoint is ideal to use when you want to round the corners of a rectangle.
Quartz uses the endpoints you supply to create two tangent lines. You also supply the radius of the circle
from which Quartz slices the arc. The center point of the arc is the intersection of two radii, each of which is
perpendicular to one of the two tangent lines. Each endpoint of the arc is a tangent point on one of the
tangent lines, as shown in Figure 3-5. The red portion of the circle is what’s actually drawn.

Figure 3-5 Defining an arc with two tangent lines and a radius

Tangent Tangent
line 1 point 1

Tangent
line 2
Radius

Tangent
point 2

If the current path already contains a subpath, Quartz appends a straight line segment from the current point
to the starting point of the arc. If the current path is empty, Quartz creates a new subpath at the starting
point for the arc and does not add the initial straight line segment.

46 The Building Blocks


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 3
Paths

Curves
Quadratic and cubic Bézier curves are algebraic curves that can specify any number of interesting curvilinear
shapes. Points on these curves are calculated by applying a polynomial formula to starting and ending points,
and one or more control points. Shapes defined in this way are the basis for vector graphics. A formula is
much more compact to store than an array of bits and has the advantage that the curve can be re-created
at any resolution.

Figure 3-6 shows a variety of curves created by drawing multiple paths independently. Each path contains
a randomly generated curve; some are filled and others are stroked.

Figure 3-6 Multiple paths; each path contains a randomly generated curve

The polynomial formulas that give to rise to quadratic and cubic Bézier curves, and the details on how to
generate the curves from the formulas, are discussed in many mathematics texts and online sources that
describe computer graphics. These details are not discussed here.

You use the function CGContextAddCurveToPoint to append a cubic Bézier curve from the current point,
using control points and an endpoint you specify. Figure 3-7 shows the cubic Bézier curve that results from
the current point, control points, and endpoint shown in the figure. The placement of the two control points
determines the geometry of the curve. If the control points are both above the starting and ending points,
the curve arches upward. If the control points are both below the starting and ending points, the curve arches
downward. If the second control point is closer to the current point (starting point) than the first control
point, the curve crosses over itself, creating a loop.

The Building Blocks 47


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 3
Paths

Figure 3-7 A cubic Bézier curve uses two control points

Point 2
Control point

Point 1 Point 3 Point 4


Current point Control point Endpoint

You can append a quadratic Bézier curve from the current point by calling the function
CGContextAddQuadCurveToPoint, and specifying a control point and an endpoint. Figure 3-8 shows two
curves that result from using the same endpoints but different control points. The control point determines
the direction that the curve arches. It’s not possible to create as many interesting shapes with a quadratic
Bézier curve as you can with a cubic one because quadratic curves use only one control point. For example,
it’s not possible to create a crossover using a single control point.

Figure 3-8 A quadratic Bézier curve uses one control point

B Control point
B Control point

A Current point C Endpoint A Current point C Endpoint

Closing a Subpath
To close the current subpath, your application should call CGContextClosePath. This function adds a line
segment from the current point to the starting point of the subpath and closes the subpath. Lines, arcs, and
curves that end at the starting point of a subpath do not actually close the subpath. You must explicitly call
CGContextClosePath to close a subpath.

Some Quartz functions treat a path’s subpaths as if they were closed by your application. Those commands
treat each subpath as if your application had called CGContextClosePath to close it, implicitly adding a
line segment to the starting point of the subpath.

After closing a subpath, if your application makes additional calls to add lines, arcs, or curves to the path,
Quartz begins a new subpath starting at the starting point of the subpath you just closed.

48 The Building Blocks


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 3
Paths

Ellipses
An ellipse is essentially a squashed circle. You create one by defining two focus points and then plotting all
the points that lie at a distance such that adding the distance from any point on the ellipse to one focus to
the distance from that same point to the other focus point is always the same value. Figure 3-9 shows multiple
paths drawn independently. Each path contains a randomly generated ellipse; some are filled and others are
stroked.

Figure 3-9 Multiple paths; each path contains a randomly generated ellipse

You can add an ellipse to the current path by calling the function CGContextAddEllipseInRect. You
supply a rectangle that defines the bounds of the ellipse. Quartz approximates the ellipse using a sequence
of Bézier curves. The center of the ellipse is the center of the rectangle. If the width and height of the rectangle
are equal (that is, a square), the ellipse is circular, with a radius equal to one-half the width (or height) of the
rectangle. If the width and height of the rectangle are unequal, they define the major and minor axes of the
ellipse.

The ellipse that is added to the path starts with a move-to operation and ends with a close-subpath operation,
with all moves oriented in the clockwise direction.

Rectangles
You can add a rectangle to the current path by calling the function CGContextAddRect. You supply a CGRect
structure that contains the origin of the rectangle and its width and height.

The rectangle that is added to the path starts with a move-to operation and ends with a close-subpath
operation, with all moves oriented in the counter-clockwise direction.

The Building Blocks 49


2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
CHAPTER 3
Paths

You can add many rectangles to the current path by calling the function CGContextAddRects and supplying
an array of CGRect structures. Figure 3-10 shows multiple paths drawn independently. Each path contains
a randomly generated rectangle; some are filled and others are stroked.

Figure 3-10 Multiple paths; each path contains a randomly generated rectangle

Creating a Path

When you want to construct a path in a graphics context, you signal Quartz by calling the function
CGContextBeginPath . Next, you set the starting point for the first shape, or subpath, in the path by calling
the function CGContextMoveToPoint. After you establish the first point, you can add lines, arcs, and curves
to the path, keeping in mind the following:

● Before you begin a new path, call the function CGContextBeginPath.

● Lines, arcs, and curves are drawn starting at the current point. An empty path has no current point; you
must call CGContextMoveToPoint to set the starting point for the first subpath or call a convenience
function that implicitly does this for you.

● When you want to close the current subpath within a path, call the function CGContextClosePath to
connect a segment to the starting point of the subpath. Subsequent path calls begin a new subpath,
even if you do not explicitly set a new starting point.

● When you draw arcs, Quartz draws a line between the current point and the starting point of the arc.

● Quartz routines that add ellipses and rectangles add a new closed subpath to the path.

● You must call a painting function to fill or stroke the path because creating a path does not draw the
path. See “Painting a Path” (page 51) for detailed information.

50 Creating a Path
2010-11-19 | © 2001, 2010 Apple Inc. All Rights Reserved.
Other documents randomly have
different content
man's advice." Nevertheless, a great many do not hear and will not
believe, and matters go on very much as they did before.
All this is natural, and will continue as long as people do not believe
the wise man's words. But, we are told, a time will come when every
one on the farm will listen to and understand the words of the wise
man, and will realize that God spoke through his lips, and that the
wise man was himself none other than God in person; and all will
have faith in his words. Meanwhile, instead of living according to the
advice of the wise man, each struggles for his own, and they slay
each other without pity, saying, "The struggle for existence is
inevitable; we cannot do otherwise."
What does it all mean? Even the beasts graze in the fields without
interfering with each other's needs, and men, after having learned
the conditions of the true life, and after being convinced that God
himself has shown them how to live the true life, follow still their evil
ways, saying that it is impossible to live otherwise. What should we
think of the people at the farm if, after having heard the words of
the wise man, they had continued to live as before, snatching the
bread from each other's mouths, fighting, and trying to grasp
everything, to their own loss? We should say that they had
misunderstood the wise man's words, and imagined things to be
different from what they really were. The wise man said to them,
"Your life here is bad; amend your ways, and it will become good."
And they imagined that the wise man had condemned their life on
the farm, and had promised them another and a better life
somewhere else. They decided that the farm was only a temporary
dwelling-place, and that it was not worth while to try to live well
there; the important thing was not to be cheated out of the other
life promised them elsewhere. This is the only way in which we can
explain the strange conduct of the people on the farm, of whom
some believed that the wise man was God, and others that he was a
man of wisdom, but all continued to live as before in defiance of the
wise man's words. They understood everything but the one
significant truth in the wise man's teachings,—that they must work
out for themselves their own peace and happiness there on the
farm, which they took for a temporary abode thinking all the time of
the better life they were to possess elsewhere.
Here is the origin of the strange declaration that the precepts of the
wise man were admirable, even divine, but that they were difficult to
practise.
Oh, if men would only cease from evil ways while waiting for the
Christ to come in his chariot of fire to their aid; if they would only
cease to invoke the law of the differentiation or integration of forces,
or any historical law whatever! None will come to their aid if they do
not aid themselves. And to aid ourselves to a better life, we need
expect nothing from heaven or from earth; we need only to cease
from ways that result in our own loss.
CHAPTER VIII.

If it be admitted that the doctrine of Jesus is perfectly reasonable,


and that it alone can give to men true happiness, what would be the
condition of a single follower of that doctrine in the midst of a world
that did not practise it at all? If all men would decide at the same
time to obey, its practice would then be possible. But one man alone
cannot act in defiance of the whole world; and so we hear
continually this plea: "If, among men who do not practise the
doctrine of Jesus, I alone obey it; if I give away all that I possess; if
I turn the other cheek; if I refuse to take an oath or to go to war, I
should find myself in profound isolation; if I did not die of hunger, I
should be beaten; if I survived that, I should be cast into prison; I
should be shot, and all the happiness of my life—my life itself—
would be sacrificed in vain."
This plea is founded upon the doctrine of quid pro quo, which is the
basis of all arguments against the possibility of practising the
doctrine of Jesus. It is the current objection, and I sympathized with
it in common with all the rest of the world, until I finally broke
entirely away from the dogmas of the Church which prevented me
from understanding the true significance of the doctrine of Jesus.
Jesus prepared his doctrine as a means of salvation from the life of
perdition organized by men contrary to his precepts; and I declared
that I should be very glad to follow this doctrine if it were not for
fear of this very perdition. Jesus offered me the true remedy against
a life of perdition, and I clung to the life of perdition! from which it
was plain that I did not consider this life as a life of perdition, but as
something good, something real. The conviction that my personal,
worldly life was something real and good constituted the
misunderstanding, the obstacle, that prevented me from
comprehending Jesus' doctrine. Jesus knew the disposition of men
to regard their personal, worldly life as real and good, and so, in a
series of apothegms and parables, he taught them that they had no
right to life, and that they were given life only that they might
assure themselves of the true life by renouncing their worldly and
fantastic organization of existence.
To understand what is meant by "saving" one's life, according to the
doctrine of Jesus, we must first understand what the prophets, what
Solomon, what Buddha, what all the wise men of the world have
said about the personal life of man. But, as Pascal says, we cannot
endure to think upon this theme, and so we carry always before us a
screen to conceal the abyss of death, toward which we are
constantly moving. It suffices to reflect on the isolation of the
personal life of man, to be convinced that this life, in so far as it is
personal, is not only of no account to each separately, but that it is a
cruel jest to heart and reason. To understand the doctrine of Jesus,
we must, before all, return to ourselves, reflect soberly, undergo the
μετάνοια of which John the Baptist, the precursor of Jesus, speaks,
when addressing himself to men of clouded judgment. "Repent"
(such was his preaching); "repent, have another mind, or you shall
all perish. The axe is laid unto the root of the trees. Death and
perdition await each one of you. Be warned, turn back, repent." And
Jesus declared, "Except ye repent, ye shall all likewise perish." When
Jesus was told of the death of the Galileans massacred by Pilate, he
said:—
"Suppose ye that these Galileans were sinners above all the
Galileans, because they suffered such things? I tell you, Nay: but,
except ye repent, ye shall all likewise perish. Or those eighteen upon
whom the tower in Siloam fell, and slew them, think ye that they
were sinners above all men that dwelt in Jerusalem? I tell you. Nay:
but, except ye repent, ye shall all likewise perish." (Luke xiii. 1-5.)
If he had lived in our day, in Russia, he would have said: "Think you
that those who perished in the circus at Berditchef or on the slopes
of Koukouyef were sinners above all others? I tell you, No; but you,
if you do not repent, if you do not arouse yourselves, if you do not
find in your life that which is imperishable, you also shall perish. You
are horrified by the death of those crushed by the tower, burned in
the circus; but your death, equally as frightful and as inevitable, is
here, before you. You are wrong to conceal it or to forget it;
unlocked for, it is only more hideous."
To the people of his own time he said:—
"When ye see a cloud rise out of the west, straightway ye say, There
cometh a shower; and so it is. And when ye see the south wind
blow, ye say, There will be heat; and it cometh to pass. Ye
hypocrites, ye can discern the face of the sky and of the earth; but
how is it that ye do not discern this time? Yea, and why even of
yourselves judge ye not what is right?" (Luke xii. 54-57.)
We know how to interpret the signs of the weather; why, then, do
we not see what is before us? It is in vain that we fly from danger,
and guard our material life by all imaginable means; in spite of all,
death is before us, if not in one way, then in another; if not by
massacre, or the falling of a tower, then in our beds, amidst much
greater suffering.
Make a simple calculation, as those do who undertake any worldly
project, any enterprise whatever, such as the construction of a
house, or the purchase of an estate, such as those make who labor
with the hope of seeing their calculations realized.
"For which of you intending to build a tower, sitteth not down first,
and counteth the cost whether he have sufficient to finish it? Lest
haply, after he hath laid the foundation, and is not able to finish it,
all that behold it begin to mock him, saying, This man began to
build, and was not able to finish. Or what king, going to make war
against another king, sitteth not down first and consulteth whether
he be able with ten thousand to meet him that cometh against him
with twenty thousand?" (Luke xiv. 28-31.)
Is it not the act of a madman to labor at what, under any
circumstances, one can never finish? Death will always come before
the edifice of worldly prosperity can be completed. And if we knew
beforehand that, however we may struggle with death, it is not we,
but death, that will triumph; is it not an indication that we ought not
to struggle with death, or to set our hearts upon that which will
surely perish, but to seek to perform the task whose results cannot
be destroyed by our inevitable departure?
"And he said unto his disciples, Therefore I say unto you, Take no
thought for your life what ye shall eat; neither for the body, what ye
shall put on. The life is more than meat and the body is more than
raiment. Consider the ravens: for they neither sow nor reap; which
neither have storehouse nor barn; and God feedeth them: How
much more are ye better than the fowls? And which of you with
taking thought can add to his stature one cubit? If ye then be not
able to do that thing which is least, why take ye thought for the
rest? Consider the lilies how they grow: they toil not, they spin not;
and yet I say unto you that Solomon in all his glory was not arrayed
like one of these." (Luke xii. 22-27.)
Whatever pains we may take for our nourishment, for the care of
the body, we cannot prolong life by a single hour.[14] Is it not folly to
trouble ourselves about a thing that we cannot possibly accomplish?
We know perfectly well that our material life will end with death, and
we give ourselves up to evil to procure riches. Life cannot be
measured by what we possess; if we think so, we only delude
ourselves. Jesus tells us that the meaning of life does not lie in what
we possess or in what we can accumulate, but in something entirely
different. He says:—
"The ground of a certain rich man brought forth plentifully: And he
thought within himself, saying, What shall I do, because I have no
room where to bestow my fruits? And he said, This will I do: I will
pull down my barns, and build greater; and there will I bestow all
my fruits and my goods. And I will say to my soul, Soul, thou hast
much goods lead up for many years; take thine ease, eat, drink, and
be merry. But God said unto him, Thou fool, this night thy soul shall
be required of thee: then whose shall those things be, which thou
hast provided? So is he that layeth up treasure for himself, and is
not rich toward God." (Luke xii. 16-21.)
Death threatens us every moment; Jesus says:—
"Let your loins be girded about, and your lights burning; and ye
yourselves like unto men that wait for their lord, when he will return
from the wedding; that, when he cometh and knocketh, they may
open unto him immediately. Blessed are those servants, whom the
lord when he cometh shall find watching; ...And if he shall come in
the second watch, or come in the third watch, and find them so,
blessed are those servants. And this know, that if the goodman of
the house had known what hour the thief would come, he would
have watched, and not have suffered his house to be broken
through. Be ye therefore ready also: for the son of man cometh at
an hour when ye think not." (Luke xii. 35-40.)
The parable of the virgins waiting for the bridegroom, that of the
consummation of the age and the last judgment, as the
commentators all agree, are designed to teach that death awaits us
at every moment. Death awaits us at every moment. Life is passed
in sight of death. If we labor for ourselves alone, for our personal
future, we know that what awaits us in the future is death. And
death will destroy all the fruits of our labor. Consequently, a life for
self can have no meaning. The reasonable life is different; it has
another aim than the poor desires of a single individual. The
reasonable life consists in living in such a way that life cannot be
destroyed by death. We are troubled about many things, but only
one thing is necessary.
From the moment of his birth, man is menaced by an inevitable
peril, that is, by a life deprived of meaning, and a wretched death, if
he does not discover the thing essential to the true life. Now it is
precisely this one thing which insures the true life that Jesus reveals
to men. He invents nothing, he promises nothing through divine
power; side by side with this personal life, which is a delusion, he
simply reveals to men the truth.
In the parable of the husbandmen (Matt. xxi. 33-42), Jesus explains
the cause of that blindness in men which conceals the truth from
them, and which impels them to take the apparent for the real, their
personal life for the true life. Certain men, having leased a vineyard,
imagined that they were its masters. And this delusion leads them
into a series of foolish and cruel actions, which ends in their exile. So
each one of us imagines that life is his personal property, and that
he has a right to enjoy it in such a way as may seem to him good,
without recognizing any obligation to others. And the inevitable
consequence of this delusion is a series of foolish and cruel actions
followed by exclusion from life. And as the husbandmen killed the
servants and at last the son of the householder, thinking that the
more cruel they were, the better able they would be to gain their
ends, so we imagine that we shall obtain the greatest security by
means of violence.
Expulsion, the inevitable sentence visited upon the husbandmen for
having taken to themselves the fruits of the vineyard, awaits also all
men who imagine that the personal life is the true life. Death expels
them from life; they are replaced by others, as a consequence of the
error which led them to misconceive the meaning of life. As the
husbandmen forgot, or did not wish to remember, that they had
received a vineyard already hedged about and provided with
winepress and tower, that some one had labored for them and
expected them to labor in their turn for others;—so the men who
would live for themselves forget, or do not wish to remember, all
that has been done for them during their life; they forget that they
are under an obligation to labor in their turn, and that all the
blessings of life which they enjoy are fruits that they ought to divide
with others.
This new manner of looking at life, this μετάνοια, or repentance, is
the corner-stone of the doctrine of Jesus. According to this doctrine,
men ought to understand and feel that they are insolvent, as the
husbandmen should have understood and felt that they were
insolvent to the householder, unable to pay the debt contracted by
generations past, present, and to come, with the overruling power.
They ought to feel that every hour of their existence is only a
mortgage upon this debt, and that every man who, by a selfish life,
rejects this obligation, separates himself from the principle of life,
and so forfeits life. Each one should remember that in striving to
save his own life, his personal life, he loses the true life, as Jesus so
many times said. The true life is the life which adds something to
the store of happiness accumulated by past generations, which
increases this heritage in the present, and hands it down to the
future. To take part in this true life, man should renounce his
personal will for the will of the Father, who gives this life to man. In
John viii. 35, we read:—
"And the servant abideth not in the house forever: but the son
abideth forever."
That is, only the son who observes the will of the father shall have
eternal life. Now, the will of the Father of Life is not the personal,
selfish life, but the filial life of the son of man; and so a man saves
his life when he considers it as a pledge, as something confided to
him by the Father for the profit of all, as something with which to
live the life of the son of man.
A man, about to travel into a far country, called his servants together
and divided among them his goods. Although receiving no precise
instructions as to the manner in which they were to use these
goods, some of the servants understood that the goods still
belonged to the master, and that they ought to employ them for the
master's gain. And the servants who had labored for the good of the
master were rewarded, while the others, who had not so labored,
were despoiled even of what they had received. (Matt. xxv. 14-46.)
The life of the son of man has been given to all men, and they know
not why. Some of them understand that life is not for their personal
use, but that they must use it for the good of the son of man;
others, feigning not to understand the true object of life, refuse to
labor for the son of man; and those that labor for the true life will be
united with the source of life; those that do not so labor, will lose the
life they already have. Jesus tells us in what the service of the son of
man consists and what will be the recompense of that service. The
son of man, endowed with kingly authority, will call upon the faithful
to inherit the true life; they have fed the hungry, given drink to the
thirsty, clothed and consoled the wretched, and in so doing they
have ministered to the son of man, who is the same in all men; they
have not lived the personal life, but the life of the son of man, and
they are given the life eternal.
According to all the Gospels, the object of Jesus' teaching was the
life eternal. And, strange as it may seem, Jesus, who is supposed to
have been raised in person, and to have promised a general
resurrection,—Jesus not only said nothing in affirmation of individual
resurrection and individual immortality beyond the grave, but on the
contrary, every time that he met with this superstition (introduced at
this period into the Talmud, and of which there is not a trace in the
records of the Hebrew prophets), he did not fail to deny its truth.
The Pharisees and the Sadducees were constantly discussing the
subject of the resurrection of the dead. The Pharisees believed in
the resurrection of the dead, in angels, and in spirits (Acts xxiii. 8),
but the Sadducees did not believe in resurrection, or angel, or spirit.
We do not know the source of the difference in belief, but it is
certain that it was one of the polemical subjects among the
secondary questions of the Hebraic doctrine that were constantly
under discussion in the Synagogues. And Jesus not only did not
recognize the resurrection, but denied it every time he met with the
idea. When the Sadducees demanded of Jesus, supposing that he
believed with the Pharisees in the resurrection, to which of the seven
brethren the woman should belong, he refuted with clearness and
precision the idea of individual resurrection, saying that on this
subject they erred, knowing neither the Scriptures nor the power of
God. Those who are worthy of resurrection, he said, will remain like
the angels of heaven (Mark xii. 21-24); and with regard to the dead:

"Have ye not read in the book of Moses, how in the bush God spake
unto him, saying, I am the God of Abraham, and the God of Isaac,
and the God of Jacob?[15] He is not the God of the dead, but the
God of the living: ye, therefore, do greatly err." (Mark xii. 26, 27.)
Jesus' meaning was that the dead are living in God. God said to
Moses, "I am the God of Abraham, and of Isaac, and of Jacob." To
God, all those who have lived the life of the son of man, are living.
Jesus affirmed only this, that whoever lives in God, will be united to
God; and he admitted no other idea of the resurrection. As to
personal resurrection, strange as it may appear to those who have
never carefully studied the Gospels for themselves, Jesus said
nothing about it whatever.
If, as the theologians teach, the foundation of the Christian faith is
the resurrection of Jesus, is it not strange that Jesus, knowing of his
own resurrection, knowing that in this consisted the principal dogma
of faith in him—is it not strange that Jesus did not speak of the
matter at least once, in clear and precise terms? Now, according to
the canonical Gospels, he not only did not speak of it in clear and
precise terms; he did not speak of it at all, not once, not a single
word.
The doctrine of Jesus consisted in the elevation of the son of man,
that is, in the recognition on the part of man, that he, man, was the
son of God. In his own individuality Jesus personified the man who
has recognized the filial relation with God. He asked his disciples
whom men said that he was—the son of man? His disciples replied
that some took him for John the Baptist, and some for Elijah. Then
came the question, "But whom say ye that I am?" And Peter
answered, "Thou art the Messiah, the son of the living God." Jesus
responded, "Flesh and blood hath not revealed it unto thee, but my
Father which is in heaven;" meaning that Peter understood, not
through faith in human explanations, but because, feeling himself to
be the son of God, he understood that Jesus was also the son of
God. And after having explained to Peter that the true faith is
founded upon the perception of the filial relation to God, Jesus
charged his other disciples that they should tell no man that he was
the Messiah. After this, Jesus told them that although he might
suffer many things and be put to death, he, that is his doctrine,
would be triumphantly re-established. And these words are
interpreted as a prophecy of the resurrection (Matt. xvi. 13-21).

Of the thirteen passages[16] which are interpreted as prophecies of


Jesus in regard to his own resurrection, two refer to Jonah in the
whale's belly, another to the rebuilding of the temple. The others
affirm that the son of man shall not be destroyed; but there is not a
word about the resurrection of Jesus. In none of these passages is
the word "resurrection" found in the original text. Ask any one who
is ignorant of theological interpretations, but who knows Greek, to
translate them, and he will never agree with the received versions.
In the original we find two different words, ἀνίστημι and ἐγείρω,
which are rendered in the sense of resurrection; one of these words
means to "re-establish"; the other means "to awaken, to rise up, to
arouse one's self." But neither the one nor the other can ever, in any
case, mean to "resuscitate"—to raise from the dead. With regard to
these Greek words and the corresponding Hebrew word, qum, we
have only to examine the scriptural passages where these words are
employed, as they are very frequently, to see that in no case is the
meaning "to resuscitate" admissible. The word voskresnovit,
auferstehn, resusciter—"to resuscitate"—did not exist in the Greek or
Hebrew tongues, for the reason that the conception corresponding
to this word did not exist. To express the idea of resurrection in
Greek or in Hebrew, it is necessary to employ a periphrasis,
meaning, "is arisen, has awakened among the dead." Thus, in the
Gospel of Matthew (xiv. 2) where reference is made to Herod's belief
that John the Baptist had been resuscitated, we read, αὐτὸς ἠγέρθη
ἀπὸ τῶν νεκρῶν, "has awakened among the dead." In the same
manner, in Luke (xvi. 31), at the close of the parable of Lazarus,
where it said that if men believe not the prophets, they would not
believe even though one be resuscitated, we find the periphrasis,
ἐάν τις ἐκ νεκρῶν ἀναστῆ, "if one arose among the dead." But, if in
these passages the words "among the dead" were not added to the
words "arose or awakened," the last two could never signify
resuscitation. When Jesus spoke of himself, he did not once use the
words "among the dead" in any of the passages quoted in support of
the affirmation that Jesus foretold his own resurrection.
Our conception of the resurrection is so entirely foreign to any idea
that the Hebrews possessed with regard to life, that we cannot even
imagine how Jesus would have been able to talk to them of the
resurrection, and of an eternal, individual life, which should be the
lot of every man. The idea of a future eternal life comes neither from
Jewish doctrine nor from the doctrine of Jesus, but from an entirely
different source. We are obliged to believe that belief in a future life
is a primitive and crude conception based upon a confused idea of
the resemblance between death and sleep,—an idea common to all
savage races.
The Hebraic doctrine (and much more the Christian doctrine) was far
above this conception. But we are so convinced of the elevated
character of this superstition, that we use it as a proof of the
superiority of our doctrine to that of the Chinese or the Hindus, who
do not believe in it at all. Not the theologians only, but the free-
thinkers, the learned historians of religions, such as Tiele, and Max
Müller, make use of the same argument. In their classification of
religions, they give the first place to those which recognize the
superstition of the resurrection, and declare them to be far superior
to those not professing that belief. Schopenhauer boldly denounced
the Hebraic religion as the most despicable of all religions because it
contains not a trace of this belief. Not only the idea itself, but all
means of expressing it, were wanting to the Hebraic religion. Eternal
life is in Hebrew hayail eolam. By olam is meant the infinite, that
which is permanent in the limits of time; olam also means "world" or
"cosmos." Universal life, and much more hayai leolam, "eternal life,"
is, according to the Jewish doctrine, the attribute of God alone. God
is the God of life, the living God. Man, according to the Hebraic idea,
is always mortal. God alone is always living. In the Pentateuch, the
expression "eternal life" is twice met with; once in Deuteronomy and
once in Genesis. God is represented as saying:—

"See now that I, even I, am he,


And there is no god with me:
I kill, and I make alive;
I have wounded, and I heal:
And there is none that can deliver out of my hand.
For I lift up my hand to heaven,
And say, As I live forever."
(Deut. xxxii. 39, 40.)

"And Jehovah said, Behold, the man is become as one of us, to


know good and evil; and now, lest he put forth his hand, and take
also the tree of life, and live forever." (Gen. iii. 22.)
These two sole instances of the use of the expression "eternal life"
in the Old Testament (with the exception of another instance in the
apocryphal book of Daniel) determine clearly the Hebraic conception
of the life of man and the life eternal. Life itself, according to the
Hebrews, is eternal, is in God; but man is always mortal: it is his
nature to be so. According to the Jewish doctrine, man as man, is
mortal. He has life only as it passes from one generation to another,
and is so perpetuated in a race. According to the Jewish doctrine,
the faculty of life exists in the people. When God said, "Ye may live,
and not die," he addressed these words to the people. The life that
God breathed into man is mortal for each separate human being;
this life is perpetuated from generation to generation, if men fulfil
the union with God, that is, obey the conditions imposed by God.
After having propounded the Law, and having told them that this
Law was to be found not in heaven, but in their own hearts, Moses
said to the people:—
"See, I have set before thee this day life and good, and death and
evil; in that I command thee this day to love the Eternal, to walk in
his ways, and to keep his commandments, that thou mayest live.... I
call heaven and earth to witness against you this day, that I have set
before thee life and death, the blessing and the curse: therefore
choose life, that thou mayest live, thou and thy seed: to love the
Eternal, to obey his voice, and to cleave unto him: for he is thy life,
and the length of thy days." (Deut. xxx. 15-19.)
The principal difference between our conception of human life and
that possessed by the Jews is, that while we believe that our mortal
life, transmitted from generation to generation, is not the true life,
but a fallen life, a life temporarily depraved,—the Jews, on the
contrary, believed this life to be the true and supreme good, given to
man on condition that he obey the will of God. From our point of
view, the transmission of the fallen life from generation to
generation is the transmission of a curse; from the Jewish point of
view, it is the supreme good to which man can attain, on condition
that he accomplish the will of God. It is precisely upon the Hebraic
conception of life that Jesus founded his doctrine of the true or
eternal life, which he contrasted with the personal and mortal life.
Jesus said to the Jews:—
"Search the Scriptures; for in them ye think ye have eternal life: and
they are they which testify of me." (John v. 39.)
To the young man who asked what he must do to have eternal life,
Jesus said in reply, "If thou wilt enter into life, keep the
commandments." He did not say "the eternal life," but simply "the
life" (Matt. xix. 17). To the same question propounded by the scribe,
the answer was, "This do, and thou shalt live" (Luke x. 28), once
more promising life, but saying nothing of eternal life. From these
two instances, we know what Jesus meant by eternal life; whenever
he made use of the phrase in speaking to the Jews, he employed it
in exactly the same sense in which it was expressed in their own
law,—the accomplishment of the will of God. In contrast with the life
that is temporary, isolated, and personal, Jesus taught of the eternal
life promised by God to Israel—with this difference, that while the
Jews believed the eternal life was to be perpetuated solely by their
chosen people, and that whoever wished to possess this life must
follow the exceptional laws given by God to Israel,—the doctrine of
Jesus holds that the eternal life is perpetuated in the son of man,
and that to obtain it we must practise the commandments of Jesus,
who summed up the will of God for all humanity.
As opposed to the personal life, Jesus taught us, not of a life beyond
the grave, but of that universal life which comprises within itself the
life of humanity, past, present, and to come. According to the Jewish
doctrine, the personal life could be saved from death only by
accomplishing the will of God as propounded in the Mosaic law. On
this condition only the life of the Jewish race would not perish, but
would pass from generation to generation of the chosen people of
God. According to the doctrine of Jesus, the personal life is saved
from death by the accomplishment of the will of God as propounded
in the commandments of Jesus. On this condition alone the personal
life does not perish, but becomes eternal and immutable, in union
with the son of man. The difference is, that while the religion given
by Moses was that of a people for a national God, the religion of
Jesus is the expression of the aspirations of all humanity. The
perpetuity of life in the posterity of a people is doubtful, because the
people itself may disappear, and perpetuity depends upon a posterity
in the flesh. Perpetuity of life, according to the doctrine of Jesus, is
indubitable, because life, according to his doctrine, is an attribute of
all humanity in the son of man who lives in harmony with the will of
God.
If we believe that Jesus' words concerning the last judgment and the
consummation of the age, and other words reported in the Gospel of
John, are a promise of a life beyond the grave for the souls of men,
—if we believe this, it is none the less true that his teachings in
regard to the light of life and the kingdom of God have the same
meaning for us that they had for his hearers eighteen centuries ago;
that is, that the only real life is the life of the son of man
conformable to the will of the Giver of Life. It is easier to admit this
than to admit that the doctrine of the true life, conformable to the
will of the Giver of Life, contains the promise of the immortality of
life beyond the grave.
Perhaps it is right to think that man, after this terrestrial life passed
in the satisfaction of personal desires, will enter upon the possession
of an eternal personal life in paradise, there to taste all imaginable
enjoyments; but to believe that this is so, to endeavor to persuade
ourselves that for our good actions we shall be recompensed with
eternal felicity, and for our bad actions punished with eternal
torments,—to believe this, does not aid us in understanding the
doctrine of Jesus, but, on the contrary, takes away the principal
foundation of that doctrine. The entire doctrine of Jesus inculcates
renunciation of the personal, imaginary life, and a merging of this
personal life in the universal life of humanity, in the life of the son of
man. Now the doctrine of the individual immortality of the soul does
not impel us to renounce the personal life; on the contrary, it affirms
the continuance of individuality forever.
The Jews, the Chinese, the Hindus, all men who do not believe in
the dogma of the fall and the redemption, conceive of life as it is. A
man lives, is united with a woman, engenders children, cares for
them, grows old, and dies. His life continues in his children, and so
passes on from one generation to another, like everything else in the
world,—stones, metals, earth, plants, animals, stars. Life is life, and
we must make the best of it.
To live for self alone, for the animal life, is not reasonable. And so
men, from their earliest existence, have sought for some reason for
living aside from the gratification of their own desires; they live for
their children, for their families, for their nation, for humanity, for all
that does not die with the personal life.
But according to the doctrine of the Church, human life, the
supreme good that we possess, is but a very small portion of
another life of which we are deprived for a season. Our life is not the
life that God intended to give us or such as is our due. Our life is
degenerate and fallen, a mere fragment, a mockery, compared with
the real life to which we think ourselves entitled. The principal object
of life is not to try to live this mortal life conformably to the will of
the Giver of Life; or to render it eternal in the generations, as the
Hebrews believed; or to identify ourselves with the will of God, as
Jesus taught; no, it is to believe that after this unreal life the true life
will begin.
Jesus did not speak of the imaginary life that we believe to be our
due, and that God did not give to us for some unexplained reason.
The theory of the fall of Adam, of eternal life in paradise, of an
immortal soul breathed by God into Adam, was unknown to Jesus;
he never spoke of it, never made the slightest allusion to its
existence. Jesus spoke of life as it is, as it must be for all men; we
speak of an imaginary life that has never existed. How, then, can we
understand the doctrine of Jesus?
Jesus did not anticipate such a singular change of view in his
disciples. He supposed that all men understood that the destruction
of the personal life is inevitable, and he revealed to them an
imperishable life. He offers true peace to them that suffer; but to
those who believe that they are certain to possess more than Jesus
gives, his doctrine can be of no value. How shall I persuade a man
to toil in return for food and clothing if this man is persuaded that he
already possesses great riches? Evidently he will pay no attention to
my exhortations. So it is with regard to the doctrine of Jesus. Why
should I toil for bread when I can be rich without labor? Why should
I trouble myself to live this life according to the will of God when I
am sure of a personal life for all eternity?
That Jesus Christ, as the second person of the Trinity, as God made
manifest in the flesh, was the salvation of men; that he took upon
himself the penalty for the sin of Adam and the sins of all men; that
he atoned to the first person of the Trinity for the sins of humanity;
that he instituted the Church and the sacraments for our salvation—
believing this, we are saved, and shall enter into the possession of
personal, eternal life beyond the grave. But meanwhile we cannot
deny that he has saved and still saves men by revealing to them
their inevitable loss, showing them that he is the way, the truth, and
the life, the true way to life instead of the false way to the personal
life that men had heretofore followed.
If there are any who doubt the life beyond the grave and salvation
based upon redemption, no one can doubt the salvation of all men,
and of each individual man, if they will accept the evidence of the
destruction of the personal life, and follow the true way to safety by
bringing their personal wills into harmony with the will of God. Let
each man endowed with reason ask himself, What is life? and What
is death? and let him try to give to life and death any other meaning
than that revealed by Jesus, and he will find that any attempt to find
in life a meaning not based upon the renunciation of self, the service
of humanity, of the son of man, is utterly futile. It cannot be doubted
that the personal life is condemned to destruction, and that a life
conformable to the will of God alone gives the possibility of
salvation. It is not much in comparison with the sublime belief in the
future life! It is not much, but it is sure.
I am lost with my companions in a snow-storm. One of them assures
me with the utmost sincerity that he sees a light in the distance, but
it is only a mirage which deceives us both; we strive to reach this
light, but we never can find it. Another resolutely brushes away the
snow; he seeks and finds the road, and he cries to us, "Go not that
way, the light you see is false, you will wander to destruction; here is
the road, I feel it beneath my feet; we are saved." It is very little, we
say. We had faith in that light that gleamed in our deluded eyes, that
told us of a refuge, a warm shelter, rest, deliverance,—and now in
exchange for it we have nothing but the road. Ah, but if we continue
to travel toward the imaginary light, we shall perish; if we follow the
road, we shall surely arrive at a haven of safety.
What, then, must I do if I alone understand the doctrine of Jesus,
and I alone have trust in it among a people who neither understand
it nor obey it? What ought I to do, to live like the rest of the world,
or to live according to the doctrine of Jesus? I understood the
doctrine of Jesus as expressed in his commandments, and I believed
that the practice of these commandments would bring happiness to
me and to all men. I understood that the fulfilment of these
commandments is the will of God, the source of life. More than this,
I saw that I should die like a brute after a farcical existence if I did
not fulfil the will of God, and that the only chance of salvation lay in
the fulfilment of His will. In following the example of the world about
me, I should unquestionably act contrary to the welfare of all men,
and, above all, contrary to the will of the Giver of Life; I should
surely forfeit the sole possibility of bettering my desperate condition.
In following the doctrine of Jesus, I should continue the work
common to all men who had lived before me; I should contribute to
the welfare of my fellows, and of those who were to live after me; I
should obey the command of the Giver of Life; I should seize upon
the only hope of salvation.

The circus at Berditchef[17] is in flames. A crowd of people are


struggling before the only place of exit,—a door that opens inward.
Suddenly, in the midst of the crowd, a voice rings out: "Back, stand
back from the door; the closer you press against it, the less the
chance of escape; stand back; that is your only chance of safety!"
Whether I am alone in understanding this command, or whether
others with me also hear and understand, I have but one duty, and
that is, from the moment I have heard and understood, to fall back
from the door and to call upon every one to obey the voice of the
saviour. I may be suffocated, I may be crushed beneath the feet of
the multitude, I may perish; my sole chance of safety is to do the
one thing necessary to gain an exit. And I can do nothing else. A
saviour should be a saviour, that is, one who saves. And the
salvation of Jesus is the true salvation. He came, he preached his
doctrine, and humanity is saved.
The circus may burn in an hour, and those penned up in it may have
no time to escape. But the world has been burning for eighteen
hundred years; it has burned ever since Jesus said, "I am come to
send fire on the earth;" and I suffer as it burns, and it will continue
to burn until humanity is saved. Was not this fire kindled that men
might have the felicity of salvation? Understanding this, I understood
and believed that Jesus is not only the Messiah, that is, the Anointed
One, the Christ, but that he is in truth the Saviour of the world. I
know that he is the only way, that there is no other way for me or
for those who are tormented with me in this life. I know, that for me
as for all, there is no other safety than the fulfilment of the
commandments of Jesus, who gave to all humanity the greatest
conceivable sum of benefits.
Would there be great trials to endure? Should I die in following the
doctrine of Jesus? This question did not alarm me. It might seem
frightful to any one who does not realize the nothingness and
absurdity of an isolated personal life, and who believes that he will
never die. But I know that my life, considered in relation to my
individual happiness, is, taken by itself, a stupendous farce, and that
this meaningless existence will end in a stupid death. Knowing this, I
have nothing to fear. I shall die as others die who do not observe the
doctrine of Jesus; but my life and my death will have a meaning for
myself and for others. My life and my death will have added
something to the life and salvation of others, and this will be in
accordance with the doctrine of Jesus.
CHAPTER IX.

Let all the world practise the doctrine of Jesus, and the reign of God
will come upon earth; if I alone practise it, I shall do what I can to
better my own condition and the condition of those about me. There
is no salvation aside from the fulfilment of the doctrine of Jesus. But
who will give me the strength to practise it, to follow it without
ceasing, and never to fail? "Lord, I believe; help thou mine unbelief."
The disciples called upon Jesus to strengthen their faith. "When I
would do good," says the apostle Paul, "evil is present with me." It is
hard to work out one's salvation.
A drowning man calls for aid. A rope is thrown to him, and he says:
"Strengthen my belief that this rope will save me. I believe that the
rope will save me; but help my unbelief." What is the meaning of
this? If a man will not seize upon his only means of safety, it is plain
that he does not understand his condition.
How can a Christian who professes to believe in the divinity of Jesus
and of his doctrine, whatever may be the meaning that he attaches
thereto, say that he wishes to believe, and that he cannot believe?
God comes upon earth, and says, "Fire, torments, eternal darkness
await you; and here is your salvation—fulfil my doctrine." It is not
possible that a believing Christian should not believe and profit by
the salvation thus offered to him; it is not possible that he should
say, "Help my unbelief." If a man says this, he not only does not
believe in his perdition, but he must be certain that he shall not
perish.
A number of children have fallen from a boat into the water. For an
instant their clothes and their feeble struggles keep them on the
surface of the stream, and they do not realize their danger. Those in
the boat throw out a rope. They warn the children against their peril,
and urge them to grasp the rope (the parables of the woman and
the piece of silver, the shepherd and the lost sheep, the marriage
feast, the prodigal son, all have this meaning), but the children do
not believe; they refuse to believe, not in the rope, but that they are
in danger of drowning. Children as frivolous as themselves have
assured them that they can continue to float gaily along even when
the boat is far away. The children do not believe; but when their
clothes are saturated, the strength of their little arms exhausted,
they will sink and perish. This they do not believe, and so they do
not believe in the rope of safety.
Just as the children in the water will not grasp the rope that is
thrown to them, persuaded that they will not perish, so men who
believe in the resurrection of the soul, convinced that there is no
danger, do not practise the commandments of Jesus. They do not
believe in what is certain, simply because they do believe in what is
uncertain. It is for this cause they cry, "Lord, strengthen our faith,
lest we perish." But this is impossible. To have the faith that will save
them from perishing, they must cease to do what will lead them to
perdition, and they must begin to do something for their own safety;
they must grasp the rope of safety. Now this is exactly what they do
not wish to do; they wish to persuade themselves that they will not
perish, although they see their comrades perishing one after another
before their very eyes. They wish to persuade themselves of the
truth of what does not exist, and so they ask to be strengthened in
faith. It is plain that they have not enough faith, and they wish for
more.
When I understood the doctrine of Jesus, I saw that what these men
call faith is the faith denounced by the apostle James:[18]—
"What doth it profit, my brethren, if a man believe he hath faith, but
hath not works? can that faith save him? If a brother or sister be
naked and in lack of daily food, and one of you say unto them, Go in
peace, be ye warmed and filled; and yet ye give them not the things
needful to the body; what doth it profit? Even so faith, if it have not
works, is dead in itself. But some one will say, Thou hast faith, and I
have works: Shew me thy faith which is without works, and I, by my
works, will show thee my faith. Thou believest there is one God;
thou doest well: the demons also believe, and tremble. But wilt thou
know, O vain man, that faith without works is dead? Was not
Abraham our father justified by works when he offered up Isaac his
son upon the altar? Thou seest that faith wrought with his works,
and by works was faith made perfect.... Ye see that by works a man
is justified, and not only by faith.... For as the body without the spirit
is dead, so faith is dead without works." (James ii. 14-26.)
James says that the indication of faith is the acts that it inspires, and
consequently that a faith which does not result in acts is of words
merely, with which one cannot feed the hungry, or justify belief, or
obtain salvation. A faith without acts is not faith. It is only a
disposition to believe in something, a vain affirmation of belief in
something in which one does not really believe. Faith, as the apostle
James defines it, is the motive power of actions, and actions are a
manifestation of faith.
The Jews said to Jesus: "What signs shewest thou then, that we
may see, and believe thee? what dost thou work?" (John vi. 30. See
also Mark xv. 32; Matt. xxvii. 42). Jesus told them that their desire
was vain, and that they could not be made to believe what they did
not believe. "If I tell you," he said, "ye will not believe" (Luke xxii.
67); "I told you, and ye believed not.... But ye believe not because
ye are not of my sheep" (John x. 25, 26).
The Jews asked exactly what is asked by Christians brought up in
the Church; they asked for some outward sign which should make
them believe in the doctrine of Jesus. Jesus explained that this was
impossible, and he told them why it was impossible. He told them
that they could not believe because they were not of his sheep; that
is, they did not follow the road he had pointed out. He explained
why some believed, and why others did not believe, and he told
them what faith really was. He said: "How can ye believe which
receive your doctrine (δόξα[19]) one of another, and seek not the
doctrine that cometh only from God?" (John v. 44).
To believe, Jesus says, we must seek for the doctrine that comes
from God alone.
"He that speaketh of himself seeketh (to extend) his own doctrine,
δόξαν τὴν ἴδιαν, but he that seeketh (to extend) the doctrine of him
that sent him, the same is true, and no untruth is in him." (John vii.
18.)
The doctrine of life, δόξα, is the foundation of faith, and actions
result spontaneously from faith. But there are two doctrines of life:
Jesus denies the one and affirms the other. One of these doctrines, a
source of all error, consists of the idea that the personal life is one of
the essential and real attributes of man. This doctrine has been
followed, and is still followed, by the majority of men; it is the
source of divergent beliefs and acts. The other doctrine, taught by
Jesus and by all the prophets, affirms that our personal life has no
meaning save through fulfilment of the will of God. If a man confess
a doctrine that emphasizes his own personal life, he will consider
that his personal welfare is the most important thing in the world,
and he will consider riches, honors, glory, pleasure, as true sources
of happiness; he will have a faith in accordance with his inclination,
and his acts will always be in harmony with his faith. If a man
confess a different doctrine, if he find the essence of life in fulfilment
of the will of God in accordance with the example of Abraham and
the teaching and example of Jesus, his faith will accord with his
principles, and his acts will be conformable to his faith. And so those
who believe that true happiness is to be found in the personal life
can never have faith in the doctrine of Jesus. All their efforts to fix
their faith upon it will be always vain. To believe in the doctrine of
Jesus, they must look at life in an entirely different way. Their
actions will coincide always with their faith and not with their
intentions and their words.
In men who demand of Jesus that he shall work miracles we may
recognize a desire to believe in his doctrine; but this desire never
can be realized in life, however arduous the efforts to obtain it. In
vain they pray, and observe the sacraments, and give in charity, and
build churches, and convert others; they cannot follow the example
of Jesus because their acts are inspired by a faith based upon an
entirely different doctrine from that which they confess. They could
not sacrifice an only son as Abraham was ready to do, although
Abraham had no hesitation whatever as to what he should do, just
as Jesus and his disciples were moved to give their lives for others,
because such action alone constituted for them the true meaning of
life. This incapacity to understand the substance of faith explains the
strange moral state of men, who, acknowledging that they ought to
live in accordance with the doctrine of Jesus, endeavor to live in
opposition to this doctrine, conformably to their belief that the
personal life is a sovereign good.
The basis of faith is the meaning that we derive from life, the
meaning that determines whether we look upon life as important
and good, or trivial and corrupt. Faith is the appreciation of good
and of evil. Men with a faith based upon their own doctrines do not
succeed at all in harmonizing this faith with the faith inspired by the
doctrine of Jesus; and so it was with the early disciples. This
misapprehension is frequently referred to in the Gospels in clear and
decisive terms. Several times the disciples asked Jesus to strengthen
their faith in his words (Matt. xx. 20-28; Mark x. 35-48). After the
message, so terrible to every man who believes in the personal life
and who seeks his happiness in the riches of this world, after the
words, "How hardly shall they that have riches enter into the
kingdom of God," and after words still more terrible for men who
believe only in the personal life, "Sell whatsoever thou hast and give
to the poor;" after these warning words Peter asked, "Behold, we
have forsaken all and followed thee; what shall we have therefore?"
Then James and John and, according to the Gospel of Matthew, their
mother, asked him that they might be allowed to sit with him in
glory. They asked Jesus to strengthen their faith with a promise of
future recompense. To Peter's question Jesus replied with a parable
(Matt. xx. 1-16); to James he replied that they did not know what
they asked; that they asked what was impossible; that they did not
understand the doctrine, which meant a renunciation of the personal
life, while they demanded personal glory, a personal recompense;
that they should drink the cup he drank of (that is, live as he lived),
but to sit upon his right hand and upon his left was not his to give.
And Jesus added that the great of this world had their profit and
enjoyment of glory and personal power only in the worldly life; but
that his disciples ought to know that the true meaning of human life
is not in personal happiness, but in ministering to others; "the son of
man came not to be ministered unto, but to minister, and to give his
life a ransom for many." In reply to the unreasonable demands
which revealed their slowness to understand his doctrine, Jesus did
not command his disciples to have faith in his doctrine, that is, to
modify the ideas inspired by their own doctrine (he knew that to be
impossible), but he explained to them the meaning of that life which
is the basis of true faith, that is, taught them how to discern good
from evil, the important from the secondary.
To Peter's question, "What shall we receive?" Jesus replies with the
parable of the laborers in the vineyard (Matt. xx. 1-16), beginning
with the words "For the kingdom of heaven is like unto a man that is
a householder," and by this means Jesus explains to Peter that
failure to understand the doctrine is the cause of lack of faith; and
that remuneration in proportion to the amount of work done is
important only from the point of view of the personal life.
This faith is based upon the presumption of certain imaginary rights;
but a man has a right to nothing; he is under obligations for the
good he has received, and so he can exact nothing. Even if he were
to give up his whole life to the service of others, he could not pay
the debt he has incurred, and so he cannot complain of injustice. If
a man sets a value upon his rights to life, if he keeps a reckoning
with the Overruling Power from whom he has received life, he
proves simply that he does not understand the meaning of life. Men
who have received a benefit act far otherwise. The laborers
employed in the vineyard were found by the householder idle and
unhappy; they did not possess life in the proper meaning of the
term. And then the householder gave them the supreme welfare of
life,—work. They accepted the benefits offered, and were
discontented because their remuneration was not graduated
according to their imaginary deserts. They did the work, believing in
their false doctrine of life and work as a right, and consequently with
an idea of the remuneration to which they were entitled. They did
not understand that work is the supreme good, and that they should
be thankful for the opportunity to work, instead of exacting
payment. And so all men who look upon life as these laborers looked
upon it, never can possess true faith. This parable of the laborers,
related by Jesus in response to the request by his disciples that he
strengthen their faith, shows more clearly than ever the basis of the
faith that Jesus taught.
When Jesus told his disciples that they must forgive a brother who
trespassed against them not only once, but seventy times seven
times, the disciples were overwhelmed at the difficulty of observing
this injunction, and said, "Increase our faith," just as a little while
before they had asked, "What shall we receive?" Now they uttered
the language of would-be Christians: "We wish to believe, but
cannot; strengthen our faith that we may be saved; make us
believe" (as the Jews said to Jesus when they demanded miracles);
"either by miracles or promises of recompense, make us to have
faith in our salvation."
The disciples said what we all say: "How pleasant it would be if we
could live our selfish life, and at the same time believe that it is far
better to practise the doctrine of God by living for others." This
disposition of mind is common to us all; it is contrary to the meaning
of the doctrine of Jesus, and yet we are astonished at our lack of
faith. Jesus disposed of this misapprehension by means of a parable
illustrating true faith. Faith cannot come of confidence in his words;
faith can come only of a consciousness of our condition; faith is
based only upon the dictates of reason as to what is best to do in a
given situation. He showed that this faith cannot be awakened in
others by promises of recompense or threats of punishment, which
can only arouse a feeble confidence that will fail at the first trial; but
that the faith which removes mountains, the faith that nothing can
shatter, is inspired by the consciousness of our inevitable loss if we
do not profit by the salvation that is offered.
To have faith, we must not count on any promise of recompense; we
must understand that the only way of escape from a ruined life is a
life conformable to the will of the Master. He who understands this
will not ask to be strengthened in his faith, but will work out his
salvation without the need of any exhortation. The householder,
when he comes from the fields with his workman, does not ask the
latter to sit down at once to dinner, but directs him to attend first to
other duties and to wait upon him, the master, and then to take his
place at the table and dine. This the workman does without any
sense of being wronged; he does not boast of his labor nor does he
demand recognition or recompense, for he knows that labor is the
inevitable condition of his existence and the true welfare of his life.
So Jesus says that when we have done all that we are commanded
to do, we have only fulfilled our duty. He who understands his
relations to his master will understand that he has life only as he
obeys the master's will; he will know in what his welfare consists,
and he will have a faith that does not demand the impossible. This is
the faith taught by Jesus, which has for its foundation a thorough
perception of the true meaning of life. The source of faith is light:—
"That was the true light which lighteth every man that cometh into
the world. He was in the world, and the world was made by him,
and the world knew him not. He came unto his own, and his own
received him not. But as many as received him, to them gave he the
right to become the children of God, even to them that believe on
his name." (John i. 9-12.)
"And this is the condemnation, that light is come into the world, and
men loved darkness rather than light, because their deeds were evil.
For every one that doeth ill hateth the light, and cometh not to the
light, lest his works should be reproved. But he that doeth the truth
cometh to the light, that his works may be made manifest, because
they have been wrought in God." (John iii. 19-21.)
He who understands the doctrine of Jesus will not ask to be
strengthened in his faith. The doctrine of Jesus teaches that faith is
inspired by the light of truth. Jesus never asked men to have faith in
his person; he called upon them to have faith in truth. To the Jews
he said:—
"Ye seek to kill me, a man that hath told you the truth which I have
heard of God." (John viii. 40.)
"Which of you convicteth me of sin? If I say truth, why do ye not
believe me?" (John viii. 46.)
"To this end have I been born, and to this end am I come into the
world, that I should bear witness unto the truth. Every one that is of
the truth heareth my voice." (John xviii. 37.)
To his disciples he said:—
"I am the way, and the truth, and the life." (John xiv. 6.)
"The Father ... shall give you another Comforter, that he may be with
you forever, even the Spirit of truth: whom the world cannot receive;
for it beholdeth him not, neither knoweth him: ye know him; for he
abideth with you, and shall be in you." (John xiv. 16, 17.)
Jesus' doctrine, then, is truth, and he himself is truth. The doctrine
of Jesus is the doctrine of truth. Faith in Jesus is not belief in a
system based upon his personality, but a consciousness of truth. No
one can be persuaded to believe in the doctrine of Jesus, nor can
any one be stimulated by any promised reward to practise it. He who
understands the doctrine of Jesus will have faith in him, because this
doctrine is true. He who knows the truth indispensable to his
happiness must believe in it, just as a man who knows that he is
drowning grasps the rope of safety. Thus, the question, What must I
do to believe? is an indication that he who asks it does not
understand the doctrine of Jesus.
CHAPTER X.

We say, It is difficult to live according to the doctrine of Jesus! And


why should it not be difficult, when by our organization of life we
carefully hide from ourselves our true situation; when we endeavor
to persuade ourselves that our situation is not at all what it is, but
that it is something else? We call this faith, and regarding it as
sacred, we endeavor by all possible means, by threats, by flattery,
by falsehood, by stimulating the emotions, to attract men to its
support. In this mad determination to believe what is contrary to
sense and reason, we reach such a degree of aberration that we are
ready to take as an indication of truth the very absurdity of the
object in whose behalf we solicit the confidence of men. Are there
not Christians who are ready to declare with enthusiasm "Credo quia
absurdum," supposing that the absurd is the best medium for
teaching men the truth? Not long ago a man of intelligence and
great learning said to me that the Christian doctrine had no
importance as a moral rule of life. Morality, he said, must be sought
in the teachings of the Stoics and the Brahmins, and in the Talmud.
The essence of the Christian doctrine is not in morality, he said, but
in the theosophical doctrine propounded in its dogmas. According to
this I ought to prize in the Christian doctrine not what it contains of
eternal good to humanity, not its teachings indispensable to a
reasonable life; I ought to regard as the most important element of
Christianity that portion of it which it is impossible to understand,
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like