Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the scale when using UIGraphicsImageRenderer

Tags:

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)

like image 644
Jordan H Avatar asked Jun 27 '16 04:06

Jordan H


People also ask

Is uigraphicsimagerenderer the next big innovation for drawing images on iOS?

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.

What is uigraphicsimagerenderer?

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.

How to draw a resized 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. 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.

How to change the size of a uiimage?

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.


1 Answers

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.

like image 50
TwoStraws Avatar answered Dec 24 '22 21:12

TwoStraws