Episode #287
Images
Series: Dive Into Core Graphics

Episode #287
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.
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.