Episode #287

Images

Series: Dive Into Core Graphics

7 minutes
Published on July 14, 2017

This video is only available to subscribers. Get access to this video and 572 others.

Sam shows how to use Core Graphics to draw images, which you might want to do if you want to blend techniques we’ve seen so far, such as clipping paths or gradients. Drawing images with Core Graphics is also useful to resize images if needed (perhaps if the API is returning one that is too large and you want to cache a thumbnail on device). You’ll also learn about a handy function to help you with aspect ratio math!

Links

Drawing an Image the Easy Way

If you can use UIKit and don't need a ton of customization, you can draw like this:

let image = #imageLiteral(resourceName: "Yosemite@2x.png")
image.draw(in: bounds)

This will draw the image in the current context.

Drawing the Hard Way

With Core Graphics you have more control over how the drawing happens. We’ll make use of a little-known function from AVFoundation called AVMakeRect. With this you can skip the aspect ratio math to make sure that you draw an image without stretching.

context.saveGState()

context.translateBy(x: bounds.midX, y: bounds.midY)
context.scaleBy(x: 1, y: -1)
context.translateBy(x: -bounds.midX, y: -bounds.midY)

let rect = AVMakeRect(aspectRatio: image.size, insideRect: bounds)
context.draw(image.cgImage!, in: rect)

context.setBlendMode(.overlay)

context.draw(#imageLiteral(resourceName: "Underwater@2x.png").cgImage!, in: bounds)

context.restoreGState()

Here we use the blend mode of .overlay, but you should play with the various blending modes and see what they do.

This episode uses Swift 3.0, Xcode 8.3.