3

Is there any difference between CGImageGetWidth(workingImage.CGImage) and workingImage.size.width ? Is the first faster or safer? I know that in the second case I get the value directly.

Paulw11
  • 108,386
  • 14
  • 159
  • 186
Tomasz Szulc
  • 4,217
  • 4
  • 43
  • 79

2 Answers2

6

Actually both of them returns the same result. CGImageGetWidth(Image.CGImage) returns the Bitmap image width, Image.size.width returns the UIImage width. If you ask about safe/fast, i think first one will be faster, because it comes from ApplicationServices framework and the second one is from UIKit framework. Hope this helps you..

relower
  • 1,293
  • 1
  • 10
  • 20
  • You mean one's implemented in C++ and the other in Objective-C? – trojanfoe Oct 18 '12 at 12:31
  • 2
    Apple uses C in this (and most non-Objective-C) case(s), not C++. – Jonathan Grynspan Oct 18 '12 at 12:31
  • 6
    No, they do not always return the same result! I've just resized a UIImage with methods described at http://stackoverflow.com/questions/1703100/resize-uiimage-with-aspect-ratio and http://stackoverflow.com/questions/2645768/uiimage-resize-scale-proportion , and found out that CGImageGetWidth(Image.CGImage) will return the width of the original image, not the resized width. Image.size.width however returns the scaled width. – Tafkadasoh Feb 19 '13 at 16:50
5

Assuming image is a UIImage *, CGImageGetWidth(image.CGImage) returns the width in pixels, whereas image.size.width returns the width in screen coordinates, i.e. the pixel width divided by the image.scale, which is typically the scale factor for the current display (2 on most Retina devices, 3 on iPhone 6 Plus), although it may be any arbitrary value, depending on how the image was created.

In terms of performance, I expect they are both ~ the same because they both involve one objc_msgSend(): image.size is a method call to get the size, and image.CGImage is a method call to get the CGImageRef. These are stored properties, so they are not expensive to fetch in any case.

Nick Lockwood
  • 40,865
  • 11
  • 112
  • 103