Difference between revisions of "Drawing iOS 8 2D Graphics in Swift with Core Graphics"

From Techotopia
Jump to: navigation, search
m (Text replacement - "<table border="0" cellspacing="0" width="100%">" to "<table border="0" cellspacing="0">")
m (Text replacement - "<hr> <table border="0" cellspacing="0"> <tr>" to "<!-- Ezoic - BottomOfPage - bottom_of_page --> <div id="ezoic-pub-ad-placeholder-114"></div> <!-- End Ezoic - BottomOfPage - bottom_of_page --> <hr> <table border="0" cellspacing="0"> <tr>")
Line 97: Line 97:
  
  
 +
<!-- Ezoic - BottomOfPage - bottom_of_page -->
 +
<div id="ezoic-pub-ad-placeholder-114"></div>
 +
<!-- End Ezoic - BottomOfPage - bottom_of_page -->
 
<hr>
 
<hr>
 
<table border="0" cellspacing="0">
 
<table border="0" cellspacing="0">

Revision as of 19:39, 10 May 2016

PreviousTable of ContentsNext
Subclassing and Extending the iOS 8 Collection View Flow Layout in SwiftInterface Builder Live Views and iOS 8 Embedded Frameworks


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


The ability to draw two dimensional graphics on the iPhone and iPad is provided as part of the Core Graphics Framework in the form of the Quartz 2D API. The iOS implementation of Quartz on iOS is the same implementation as that provided with Mac OS X and provides a set of C functions designed to enable the drawing of 2D graphics in the form of images, lines and shapes together with a range of fill patterns and gradients.

In this chapter we will provide an overview of Quartz 2D. A later chapter, entitled, An iOS 8 Graphics Tutorial using Core Graphics and Core Image provides a step-by-step tutorial designed to teach the basics of two dimensional drawing on iOS.


Contents


Introducing Core Graphics and Quartz 2D

Quartz 2D is a two dimensional graphics drawing engine that makes up the bulk of the UIKit Core Graphics Framework. It is a C based application programming interface (API) and as such is utilized primarily through calls to a range of C functions. Quartz 2D drawing typically takes place on a UIView object (or, more precisely a subclass thereof). Drawings are defined in terms of the paths that a line must follow and rectangular areas into which shapes (rectangles, ellipses etc) must fit.

The drawRect Method

The first time a view is displayed, and each time part of that view needs to be redrawn as a result of another event, the drawRect method of the view is called. Drawing is achieved, therefore, by subclassing the UIView class, implementing the drawRect method and placing within that method the Quartz 2D API calls to draw the graphics.

In instances where the drawRect method is not automatically called, a redraw may be forced via a call to the setNeedsDisplay or setNeedsDisplayInRect methods.


Points, Coordinates and Pixels

The Quartz 2D API functions work on the basis of points. These are essentially the x and y coordinates of a two dimensional coordinate system on the device screen with 0, 0 representing the top left hand corner of the display. These coordinates are stored in the form of CGFloat variables.

An additional C structure named CGPoint is used to contain both the x and y coordinates to specify a point on the display. Similarly, the CGSize structure stores two CGFloat values designating the width and height of an element on the screen.

Further, the position and dimension of a rectangle can be defined using the CGRect structure which contains a CGPoint (the location) and CGSize (the dimension) of a rectangular area.

Of key importance when working with points and dimensions is that these values do not correspond directly to screen pixels. In other words there is not a one to one correlation between pixels and points. Instead the underlying framework decides, based on a scale factor, where a point should appear and at what size, relative to the resolution of the display on which the drawing is taking place. This enables the same code to work on both higher and lower resolution screens (for example an iPhone 3GS screen and an iPhone 6 retina display) without the programmer having to worry about it.

For more precise drawing requirements, iOS version 4 and later allows the scale factor for the current screen to be obtained from UIScreen, UIView, UIImage, and CALayer classes allowing the correlation between pixels and points to be calculated for greater drawing precision. For iOS 3 or older the scale factor is always returned as 1.0.

The Graphics Context

Almost without exception, all Quartz API function calls require that the graphics context be passed as an argument. Each view has its own context which is responsible for performing the requested drawing tasks and subsequently rendering those drawings onto the corresponding view. The graphics context can be obtained with a call to the UIGraphicsGetCurrentContext() function which returns a result of type CGContextRef:

let context = UIGraphicsGetCurrentContext()

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

Working with Colors in Quartz 2D

The Core Graphics CGColorRef data type is used to store colors when drawing with Quartz. This data type holds information about the colorspace of the color (RGBA, CMYK or gray scale) together with a set of component values that specify both the color and the transparency of that color. For example, the color red with no transparency would be defined with the RGBA components 1.0, 0.0, 0.0, 1.0.

A colorspace can be created via a Quartz API function call. For example, to create an RGB colorspace:

let colorSpace = CGColorSpaceCreateDeviceRGB()

If the function fails to create a colorspace, it will return a nil value.

Gray scale and CMYK color spaces may similarly be created using the CGColorSpaceCreateDeviceGray() and CGColorSpaceCreateDeviceCMYK() functions respectively.

Once the colorspace has been created, the next task is to define the components. The following declaration defines a set of RGBA components for a semi-transparent blue color:

let components: [CGFloat] = [0.0, 0.0, 1.0, 0.5]

With both the colorspace and the components defined, the CGColorRef structure can be created:

let color = CGColorCreate(colorSpace, components)

The color may then be used to draw using the Quartz 2D drawing API functions.

Another useful method for creating colors involves the UIKit UIColor class. Whilst this class cannot be used directly with the Quartz function since it is a Swift class, it is possible to extract a color in CGColorRef format from the UIColor class by referencing the CGColor property.

The advantage offered by UIColor, in addition to being object oriented, is that it includes a range of convenience methods that can be used to create colors. For example, the following code uses the UIColor class to create the color red, and then accesses the CGColor property for use as an argument to the CGCreateSetStrokeColorWithColor() C function:

CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)

The color selection and transparency can be further refined using this technique simply by specifying additional components. For example:

let color = UIColor(red:1.0 green:0.3 blue:0.8 alpha:0.5)

As we can see, the use of UIColor avoids the necessity to create colorspaces and components when working with colors. Refer to the Apple documentation for more details of the range of methods provided by the UIColor class.

Summary

This chapter has covered some of the basic principles behind the drawing of two dimensional graphics on iOS 8 using the Quartz 2D API. Topics covered included obtaining the graphics context, implementing the drawRect method and the handling of colors and transparency. In An iOS 8 Swift Graphics Tutorial using Core Graphics and Core Image this theory will be put into practice with examples of how to draw a variety of shapes and images on an iOS device screen. Before moving on to the drawing tutorial, however, the next chapter will begin by exploring the Live Views feature of Interface Builder. Introduced in Xcode 6, Live Views are particularly useful when writing dynamic user interface code such as drawing graphics.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
Subclassing and Extending the iOS 8 Collection View Flow Layout in SwiftInterface Builder Live Views and iOS 8 Embedded Frameworks