Sam Sam - 1 year ago 195
Swift Question

Swift: UIGraphicsBeginImageContextWithOptions scale factor set to 0 but not applied

I used to resize an image with the following code and it used to work just fine regarding the scale factor. Now with Swift 3 I can't figure out why the scale factor is not taken into account. The image is resized but the scale factor not applied. Do you know why?

let layer = self.imageview.layer

UIGraphicsBeginImageContextWithOptions(layer.bounds.size, true, 0)

layer.render(in: UIGraphicsGetCurrentContext()!)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()

print("SCALED IMAGE SIZE IS \(scaledImage!.size)")

For example if I take a screenshot on iPhone 5 the image size will be 320*568. I used to get 640*1136 with exact same code.. What can cause the scale factor not to be applied?

When I print the scale of the image it would print 1, 2 or 3 based on the device resolution but will not be applied to the image taken from the context.

Answer Source

scaledImage!.size will not return the image size in pixel.

CGImageGetWidth and CGImageGetHeight returns the same size (in pixels) That is image.size * image.scale

If you wanna test it out, at first you have to import CoreGraphics

let imageSize = scaledImage!.size //(320,568)
let imageWidthInPixel = CGImageGetWidth(scaledImage as! CGImage) //640
let imageHeightInPixel = CGImageGetHeight(scaledImage as! CGImage) //1136
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download