5

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.

Sam
  • 1,101
  • 2
  • 13
  • 26
  • @LeoDabus already tried but it's not applied. I also tried UIScreen.main.scale. – Sam Sep 24 '16 at 08:02
  • @LeoDabus I've already checked your post before asking the question :) The question is not image specific it could be any layer. The issue is that this way to get an image from a graphic context has always applied the proper scale factor now it does not take it into account. It's more about why scale factor is not applied. – Sam Sep 24 '16 at 08:09

1 Answers1

6

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
ronan
  • 1,611
  • 13
  • 20
  • Thanks for your relevant remark. In fact this has changed with Swift 3, it used to return the size pixel before so I get confused. Thanks a lot! – Sam Sep 24 '16 at 10:57
  • Updated for Swift 4.1: ```let cgimage = scaledImage?.cgImage print("Image size = \(scaledImage?.size)") print("cgimage width = \(cgimage?.width)") print("cgimage height = \(cgimage?.height)")``` And example result: ```Image size = Optional((320.0, 320.0)) cgimage width = Optional(640) cgimage height = Optional(640)``` – Nico teWinkel Sep 14 '18 at 18:57