An iOS 10 Graphics Tutorial using Core Graphics and Core Image

From Techotopia
Jump to: navigation, search

PreviousTable of ContentsNext
Interface Builder Live Views and iOS 10 Embedded FrameworksiOS 10 Animation using UIViewPropertyAnimator


You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book


As previously discussed in Drawing iOS 10 2D Graphics with Core Graphics the Quartz 2D API is the primary mechanism by which 2D drawing operations are performed within iOS applications. Having provided an overview of Quartz 2D as it pertains to iOS development in that chapter, the focus of this chapter is to provide a tutorial that provides examples of how 2D drawing is performed. If you are new to Quartz 2D and have not yet read Drawing iOS 10 2D Graphics with Core Graphics it is recommended that you do so now before embarking on this tutorial.




The iOS Drawing Example Application

If you are reading this book sequentially and have created the LiveViewDemo project as outlined in the chapter entitled Interface Builder Live Views and iOS 10 Embedded Frameworks, then the code in this chapter may simply be placed in the draw method contained within the MyDrawView.swift file and the results viewed dynamically within the live view in the Main.storyboard file. If you have not yet completed the tutorial in Interface Builder Live Views and iOS 10 Embedded Frameworks, follow the steps in the next three sections to create a new project, add a UIView subclass and locate the draw method.

Creating the New Project

The application created in this tutorial will contain a subclassed UIView component within which the draw method will be overridden and used to perform a variety of 2D drawing operations. Create the new project by launching the Xcode development environment and selecting the option to create a new project. When prompted to select a template for the application, choose the Single View Application option and name the project Draw2D with the Devices menu set to Universal and Swift selected as the programming language.

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book


Creating the UIView Subclass

In order to draw graphics on the view it is necessary to create a subclass of the UIView object and override the draw method. In the project navigator panel located on the left-hand side of the main Xcode window Ctrl-click on the Draw2D folder entry and select New File… from the resulting menu. In the New File window, select the iOS source Cocoa Touch Class icon and click Next. On the subsequent options screen, change the Subclass of menu to UIView and the class name to Draw2D. Click Next and on the final screen click on the Create button.

Select the Main.storyboard file followed by the UIView component in either the view controller canvas or the document outline panel. Display the Identity Inspector (View -> Utilities -> Show Identity Inspector) and change the Class setting from UIView to our new class named Draw2D:


Ios 8 set draw2d class.png

Figure 63-1

Locating the draw Method in the UIView Subclass

Now that we have subclassed our application’s UIView the next step is to implement the draw method in this subclass. Fortunately Xcode has already created a template of this method for us. To locate this method, select the Draw2D.swift file in the project navigator panel. Having located the method in the file, remove the comment markers (/* and */) within which it is currently encapsulated:

import UIKit

class Draw2D: UIView {

    override func draw(_ rect: CGRect) {
        // Drawing code
    }
}   

In the remainder of this tutorial we will modify the code in the draw method to perform a variety of different drawing operations.

Drawing a Line

In order to draw a line on a device screen using Quartz 2D we first need to obtain the graphics context for the view:

let context = UIGraphicsGetCurrentContext()

Once the context has been obtained, the width of the line we plan to draw needs to be specified:

context?.setLineWidth(2.0)

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

Next, we need to create a color reference. We can do this by specifying the RGBA components of the required color (in this case opaque blue):

let colorSpace = CGColorSpaceCreateDeviceRGB()
let components: [CGFloat] = [0.0, 0.0, 1.0, 1.0]
let color = CGColor(colorSpace: colorSpace, components: components)

Using the color reference and the context we can now specify that the color is to be used when drawing the line:

context?.setStrokeColor(color!)

The next step is to move to the start point of the line that is going to be drawn:

context?.move(to: CGPoint(x: 30, y: 30))

The above line of code indicates that the start point for the line is the top left-hand corner of the device display. We now need to specify the end point of the line, in this case 300, 400:

context?.addLine(to: CGPoint(x: 300, y: 400))

Having defined the line width, color and path, we are ready to draw the line:

context?.strokePath()

Bringing this all together gives us a draw method that reads as follows:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    context?.setLineWidth(2.0)
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let components: [CGFloat] = [0.0, 0.0, 1.0, 1.0]
    let color = CGColor(colorSpace: colorSpace, components: components)
    context?.setStrokeColor(color!)
    context?.move(to: CGPoint(x: 30, y: 30))
    context?.addLine(to: CGPoint(x: 300, y: 400))
    context?.strokePath()
}

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

When compiled and run, the application should display as illustrated in Figure 63-2:


A line drawn with Core Graphics on iOS 10

Figure 63-2


Note that in the above example we manually created the colorspace and color reference. As described in Drawing iOS 10 2D Graphics with Core Graphics colors can also be created using the UIColor class. For example, the same result as outlined above can be achieved with fewer lines of code as follows:

override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()
    context?.setLineWidth(2.0)
    context?.setStrokeColor(UIColor.blue.cgColor)
    context?.move(to: CGPoint(x: 30, y: 30))
    context?.addLine(to: CGPoint(x: 300, y: 400))
    context?.strokePath()
}

Drawing Paths

As you may have noticed, in the above example we draw a single line by essentially defining the path between two points. Defining a path that comprises multiple points allows us to draw using a sequence of straight lines all connected to each other using repeated calls to the addLine(to:) method of the context. Non-straight lines may also be added to a shape using calls to, for example, the addArc method.

The following code, for example, draws a diamond shape:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    context?.setLineWidth(2.0)
    context?.setStrokeColor(UIColor.blue.cgColor)
    context?.move(to: CGPoint(x:100, y: 100))
    context?.addLine(to: CGPoint(x: 150, y: 150))
    context?.addLine(to: CGPoint(x: 100, y: 200))
    context?.addLine(to: CGPoint(x: 50, y: 150))
    context?.addLine(to: CGPoint(x: 100, y: 100))
    context?.strokePath()
}

When executed, the above code should produce output that appears as shown in Figure 63-3:


An iOS Core Graphics Path drawing

Figure 63-3


Drawing a Rectangle

Rectangles are drawn in much the same way as any other path is drawn, with the exception that the path is defined by specifying the x and y co-ordinates of the top left-hand corner of the rectangle together with the rectangle’s height and width. These dimensions are stored in a CGRect structure and passed through as an argument to the addRect method:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    context?.setLineWidth(4.0)
    context?.setStrokeColor(UIColor.blue.cgColor)
    let rectangle = CGRect(x: 60,y: 170,width: 200,height: 80)
    context?.addRect(rectangle)
    context?.strokePath()
}

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

The above code will result in the following display when compiled and executed:


An iOS Core Graphics Rectangle

Figure 63-4


Drawing an Ellipse or Circle

Circles and ellipses are drawn by defining the rectangular area into which the shape must fit and then calling the addEllipse(in:) context method:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    context?.setLineWidth(4.0)
    context?.setStrokeColor(UIColor.blue.cgColor)
    let rectangle = CGRect(x: 60,y: 170,width: 200,height: 80)
    context?.addEllipse(in: rectangle)
    context?.strokePath()
}

When compiled, the above code will produce the following graphics:


An iOS Core Graphics Ellipse

Figure 63-5


In order to draw a circle simply define a rectangle with equal length sides (a square in other words).

Filling a Path with a Color

A path may be filled with a color using a variety of Quartz 2D API functions. Rectangular and elliptical paths may be filled using the fill(rect:) and fillEllipse(in:) context methods respectively. Similarly, a path may be filled using the fillPath method. Prior to executing a fill operation, the fill color must be specified using the setFillColor method.

The following example defines a path and then fills it with the color red:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    context?.move(to: CGPoint(x: 100, y: 100))
    context?.addLine(to: CGPoint(x: 150, y: 150))
    context?.addLine(to: CGPoint(x: 100, y: 200))
    context?.addLine(to: CGPoint(x: 50, y: 150))
    context?.addLine(to: CGPoint(x: 100, y: 100))
    context?.setFillColor(UIColor.red.cgColor)
    context?.fillPath()
}

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

The above code produces the following graphics on the device or simulator display when executed:


A filled path drawn using iOS Core Graphics

Figure 63-6


The following code draws a rectangle with a blue border and then once again fills the rectangular space with red:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    context?.setLineWidth(4.0)
    context?.setStrokeColor(UIColor.blue.cgColor)
    let rectangle = CGRect(x: 60,y: 170,width: 200,height: 80)
    context?.addRect(rectangle)
    context?.strokePath()
    context?.setFillColor(UIColor.red.cgColor)
    context?.fill(rectangle)
}

When added to the example application, the resulting display should appear as follows:


An iOS Core Graphics filled and outlined rectangle

Figure 63-7


Drawing an Arc

An arc may be drawn by specifying two tangent points and a radius using the addArc context method, for example:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    context?.setLineWidth(4.0)
    context?.setStrokeColor(UIColor.blue.cgColor)
    context?.move(to: CGPoint(x: 100, y: 100))
    context?.addArc(tangent1End: CGPoint(x: 100, y: 200), 
		tangent2End: CGPoint(x: 300, y: 200), radius: 100)
    context?.strokePath()
}

The above code will result in the following graphics output:


An iOS Core Graphics Arc

Figure 63-8


Drawing a Cubic Bézier Curve

A cubic Bézier curve may be drawn by moving to a start point and then passing two control points and an end point through to the addCurve(to:) method:

override func draw(_ rect: CGRect) 
{
    let context = UIGraphicsGetCurrentContext()
    context?.setLineWidth(4.0)
    context?.setStrokeColor(UIColor.blue.cgColor)
    context?.move(to: CGPoint(x: 10, y: 10))
    context?.addCurve(to: CGPoint(x: 0, y: 50), 
			control1: CGPoint(x: 300, y: 250), 
			control2: CGPoint(x: 300, y: 40))
    context?.strokePath()
} 

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

The above code will cause the curve illustrated in Figure 63 9 to be drawn when compiled and executed in our example application:


An iOS Core Graphics Cubic Bézier Curve

Figure 63-9


Drawing a Quadratic Bézier Curve

A quadratic Bézier curve is drawn using the addQuadCurve(to:) method, providing a control and end point as arguments having first moved to the start point:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    context?.setLineWidth(4.0)
    context?.setStrokeColor(UIColor.blue.cgColor)
    context?.move(to: CGPoint(x: 10, y: 200))
    context?.addQuadCurve(to: CGPoint(x: 300, y: 200), 
		control: CGPoint(x: 150, y: 10))
    context?.strokePath()
}

The above code, when executed, will display a curve that appears as illustrated in the following figure:


An iOS Core Graphics Quadratic Bézier Curve

Figure 63-10


Dashed Line Drawing

So far in this chapter we have performed all our drawing with a solid line. Quartz also provides support for drawing dashed lines. This is achieved via the Quartz setLineDash method which takes as its arguments the following:

context – The graphics context of the view on which the drawing is to take place

phase - A floating point value that specifies how far into the dash pattern the line starts

lengths – An array containing values for the lengths of the painted and unpainted sections of the line. For example an array containing 5 and 6 would cycle through 5 painted unit spaces followed by 6 unpainted unit spaces.

count – A count of the number of items in the lengths array

For example, a [2,6,4,2] lengths array applied to a curve drawing of line thickness 5.0 will appear as follows:


An iOS Core Graphics dashed line

Figure 63-11


The corresponding draw method code that drew the above line reads as follows:

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    context?.setLineWidth(20.0)
    context?.setStrokeColor(UIColor.blue.cgColor)
    let dashArray:[CGFloat] = [2,6,4,2]
    context?.setLineDash(phase: 3, lengths: dashArray)
    context?.move(to: CGPoint(x: 10, y: 200))
    context?.addQuadCurve(to: CGPoint(x: 300, y: 200), 
		control: CGPoint(x: 150, y: 10))
    context?.strokePath()
}

Drawing Shadows

In addition to drawing shapes, Core Graphics can also be used to create shadow effects. This is achieved using the setShadow method, passing through a graphics context, offset values for the position of the shadow relative to the shape for which the shadow is being drawn and a value specifying the degree of blurring required for the shadow effect.

The following code, for example, draws an ellipse with a shadow:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    let myShadowOffset = CGSize (width: -10,  height: 15)

    context?.saveGState()
    context?.setShadow (offset: myShadowOffset, blur: 5)
    context?.setLineWidth(4.0)
    context?.setStrokeColor(UIColor.blue.cgColor)
    let rectangle = CGRect(x: 60,y: 170,width: 200,height: 80)
    context?.addEllipse(in: rectangle)
    context?.strokePath()
    context?.restoreGState()
}

When executed, the above code will produce the effect illustrated in Figure 63-12:


A shadow effect using iOS 10 Core Graphics

Figure 63-12


Drawing Gradients

Gradients are implemented using the Core Graphics CGGradient class which provides support for linear, radial and axial gradients. Use of the CGGradient class essentially involves the specification of two or more colors together with a set of location values. The location values are used to indicate the points at which the gradient should switch from one color to another as the gradient is drawn along an axis line where 0.0 represents the start of the axis and 1.0 the end point. Assume, for the purposes of an example, that you wish to create a gradient that transitions through three different colors along the gradient axis with each color being given an equal amount of space within the gradient. In this situation, three locations would be specified. The first would be 0.0 to represent the start of the gradient. Two more locations would then need to be specified for the transition points to the remaining colors. In order to equally divide the axis amongst the colors these would need to be set to 0.3333 and 0.6666 respectively.

Having configured a CGGradient instance, a linear gradient is then drawn via a call to the drawLinearGradient method of the context object, passing through the colors, locations and start and end points as arguments.

The following code, for example, draws a linear gradient using four colors with four equally spaced locations:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()

    let locations: [CGFloat] = [ 0.0, 0.25, 0.5, 0.75 ]

    let colors = [UIColor.red.cgColor,
                  UIColor.green.cgColor,
                  UIColor.blue.cgColor,
                  UIColor.yellow.cgColor]

    let colorspace = CGColorSpaceCreateDeviceRGB()

    let gradient = CGGradient(colorsSpace: colorspace,
                  colors: colors as CFArray, locations: locations)

    var startPoint = CGPoint()
    var endPoint =  CGPoint()

    startPoint.x = 0.0
    startPoint.y = 0.0
    endPoint.x = 600
    endPoint.y = 600

    context?.drawLinearGradient(gradient!,
               start: startPoint, end: endPoint, 
			options: .drawsBeforeStartLocation)
}  

When executed, the above code will generate the gradient shown in Figure 63-13:


An iOS 10 Core Graphics linear gradient

Figure 63-13

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

Radial gradients involve drawing a gradient between two circles. When the circles are positioned apart from each other and given different sizes a conical effect is achieved as shown in Figure 63-14:


A code drawn using iOS Core Graphics gradients

Figure 63-14


The code to draw the above radial gradient sets up the colors and locations for the gradient before declaring the center points and radius values for two circles. The gradient is then drawn via a call to the drawRadialGradient method:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()

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

    let colors = [UIColor.red.cgColor,
                  UIColor.green.cgColor,
                  UIColor.cyan.cgColor]

    let colorspace = CGColorSpaceCreateDeviceRGB()

    let gradient = CGGradient(colorsSpace: colorspace,
                    colors: colors as CFArray, locations: locations)

    var startPoint =  CGPoint()
    var endPoint  = CGPoint()

    startPoint.x = 100
    startPoint.y = 100
    endPoint.x = 200
    endPoint.y = 200
    let startRadius: CGFloat = 10
    let endRadius: CGFloat = 75

    context?.drawRadialGradient(gradient!, startCenter: startPoint,
                         startRadius: startRadius, endCenter: endPoint, 
				endRadius: endRadius, options: [])
}

Interesting effects may also be created by assigning a radius of 0 to the starting point circle and positioning it within the circumference of the end point circle:

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    let locations: [CGFloat] = [0.0, 1.0]

    let colors = [UIColor.white.cgColor,
                      UIColor.blue.cgColor]

    let colorspace = CGColorSpaceCreateDeviceRGB()

    let gradient = CGGradient(colorsSpace: colorspace,
                    colors: colors as CFArray, locations: locations)

    var startPoint = CGPoint()
    var endPoint = CGPoint()
    startPoint.x = 180
    startPoint.y = 180
    endPoint.x = 200
    endPoint.y = 200
    let startRadius: CGFloat = 0
    let endRadius: CGFloat = 75

    context?.drawRadialGradient (gradient!, startCenter: startPoint,
                         startRadius: startRadius, endCenter: endPoint, 
			  endRadius: endRadius,
                         options: .drawsBeforeStartLocation)
}

When executed, the above code creates the appearance of light reflecting on the surface of a shiny blue sphere:


[[Image:iso_7_draw2d_reflection.png|A glossy reflective sphere drawn with core graphics]

Figure 63-15

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

Drawing an Image into a Graphics Context

An image may be drawn into a graphics context either by specifying the coordinates of the top left-hand corner of the image (in which case the image will appear full size) or resized so that it fits into a specified rectangular area. Before we can display an image in our example application, however, that image must first be added to the project resources.

Begin by locating the desired image using the Finder and then drag and drop that image onto the project navigator panel of the Xcode main project window.

The following example draw method code displays the image in a file named tree.png full size located at 0, 0:

override func draw(_ rect: CGRect)
{
    let myImage = UIImage(named: "tree.png")
    let imagePoint = CGPoint(x: 0, y: 0)
    myImage?.draw(at: imagePoint)
}

As is evident when the application is run, the size of the image far exceeds the available screen size:


An unscaled image

Figure 63-16


Using the draw method of the UIImage object, however, we can scale the image to fit better on the screen. In this instance it is useful to identify the screen size since this changes depending on the device on which the application is running. This can be achieved using the mainScreen and bounds methods of the UIScreen class. The mainScreen method returns another UIScreen object representing the device display. Calling the bounds method of that object returns the dimensions of the display in the form of a CGRect object:

override func draw(_ rect: CGRect)
{
    let myImage = UIImage(named: "tree.png")
    let imageRect = UIScreen.main.bounds
    myImage?.draw(in: imageRect)
}

This time, the entire image fits comfortably on the screen:

A scaled image

Figure 63-17


Image Filtering with the Core Image Framework

Having covered the concept of displaying images within an iOS application, now is a good time to provide a basic overview of the Core Image Framework.

Core Image was introduced with iOS 5 and provides a mechanism for filtering and manipulating still images and videos. Included with Core Image is a wide range of different filters together with the ability to build custom filters to meet specific requirements. Examples of filters that may be applied include cropping, color effects, blurring, warping, transformations and gradients. A full listing of filters is available in Apple’s Core Image Filter Reference document which is located in the iOS Developer portal.

A CIImage object is typically initialized with a reference to the image to be manipulated. A CIFilter object is then created and configured with the type of filtering to be performed, together with any input parameters required by that filter. The CIFilter object is then instructed to perform the operation and the modified image is subsequently returned in the form of a CIImage object. The application’s CIContext reference may then be used to render the image for display to the user.

By way of an example of Core Image in action we will modify the draw method of our Draw2D example application to render the previously displayed image in a sepia tone using the CISepiaTone filter. The first step, however, is to add the CoreImage Framework to the project. This is achieved by selecting the Draw2D target at the top of the project navigator and then selecting the Build Phases tab in the main panel. Unfold the Link Binary with Libraries section of the panel, click on the + button and locate and add the CoreImage.framework library from the resulting list.

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

Having added the framework, select the Draw2D.swift file and modify draw as follows:

override func draw(_ rect: CGRect)
{
    let myimage = UIImage(named: "tree.png")
    let cimage = CIImage(image: myimage!)

    let sepiaFilter = CIFilter(name: "CISepiaTone")
    sepiaFilter!.setDefaults()
    sepiaFilter!.setValue(cimage, forKey: "inputImage")
    sepiaFilter!.setValue(NSNumber(value: 0.8 as Float),
                forKey: "inputIntensity")

    let image = sepiaFilter!.outputImage

    let context = CIContext(options: nil)

    let cgImage = context.createCGImage(image!,
                from: image!.extent)

    let resultImage = UIImage(cgImage: cgImage!)
    let imageRect = UIScreen.main.bounds
    resultImage.draw(in: imageRect)
}

The method begins by loading the image file used in the previous section of this chapter. Since Core Image works on CIImage objects it is then necessary to convert the UIImage to a CIImage. Next a new CIFilter object is created and initialized with the CISepiaTone filter. The filter is then set to the default settings before being configured with the input image (in this case our cimage object) and the value of intensity of the filter (0.8).

With the filter object configured, its outputImage method is called to perform the manipulation and the resulting modified image assigned to a new CImage object. The CIContext reference for the application is then obtained and used to convert the CImage object to a CGImageRef object. This, in turn, is converted to a UIImage object which is then displayed to the user using the object’s draw method. When compiled and run the image will appear in a sepia tone.

Summary

By subclassing the UIView class and overriding the draw method a variety of 2D graphics drawing functions may be performed on the view canvas. In this chapter we have explored some of the graphics drawing capabilities of Quartz 2D to draw a variety of line types and paths and to present images on the iOS device screen.

Introduced in iOS 5, the Core Image Framework is designed specifically for the filtering and manipulation of images and video. In this chapter we have provided a brief overview of Core Image and worked through a simple example that applied a sepia tone filter to an image.


You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book



PreviousTable of ContentsNext
Interface Builder Live Views and iOS 8 Embedded FrameworksiOS 10 Animation using UIViewPropertyAnimator