Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
UIGraphicsEndImageContext()

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

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.

like image 745
Sam Avatar asked Sep 24 '16 07:09

Sam


1 Answers

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
like image 168
ronan Avatar answered Nov 15 '22 03:11

ronan