By default UIGraphicsImageRenderer
sets the scale to the device's screen scale, on iPhone 6s it's 2x and iPhone 6s Plus 3x, therefore even though you've given it a size with dimension 300 it's creating it at either 600 or 900 depending on which device is being used. When you want to ensure it's always 300, how do you set the scale?
let outputBounds = CGRect(x: 0, y: 0, width: 300, height: 300)
let renderer = UIGraphicsImageRenderer(bounds: outputBounds)
let image = renderer.image { context in
//...
}
Previously you would set the scale via the last parameter here:
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 1)
We’ve experienced a similar shift on iOS starting with iOS 10, though many engineers have yet to discover or adopt the latest innovation for drawing images — UIGraphicsImageRenderer. Core Graphics, based on the Quartz drawing engine, has provided iOS developers with lightweight 2D rendering capabilities since iOS 2.
In contrast, UIGraphicsImageRenderer is built for tomorrow in mind: It’s automagically fully color managed. For example, on the beautiful 9.7 inch iPad pro you’ll get a wide color context. It’s a first class object.
This new scaled size must preserve the aspect ratio of the original image. The next step is to create a new scaled UIImage from the original UIImage. One way to draw a resized UIImage is to use the UIGraphicsImageRenderer. The last step is to combine the code snippets for resizing and drawing into a UIImage extension.
The first step is to determine the new scaled size of the original UIImage. This new scaled size must preserve the aspect ratio of the original image. The next step is to create a new scaled UIImage from the original UIImage.
You should use the UIGraphicsImageRendererFormat
class when creating your UIGraphicsImageRenderer
. If you want to write exact pixels rather than scaled points, use something like this:
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let renderer = UIGraphicsImageRenderer(size: yourImageSize, format: format)
let image = renderer.image { ctx in
// etc
}
I'm keeping a list of iOS 10 code examples and will add one based on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With