2

To determine the ratio at which to scale an image, I'm using the following code (borrowed from Trevor Harmon's UIImage+Resize):

CGFloat horizontalRatio = 600 / CGImageGetWidth(imageRef);
CGFloat verticalRatio = 600 / CGImageGetHeight(imageRef);
CGFloat ratio = MAX(horizontalRatio, verticalRatio);

The 600 represents the maximum size I want for the scaled image. CGImageGetWidth and CGImageGetHeight return a size_t which, according to ARC, evaluate to an unsigned long on the iPhone platform (iOS 5). The problem with the present code is that ratio always evaluates 0.0000. The width and height of imageRef are actually w=768, h=780, so the ratio should be MAX(0.781, 0.769) = 0.78. How do I this?

P.S. When I used the code above for UIImage's initWithCGImage:scale:orientation: I found that scale works differently than I'd expected: passing in a ratio of 0.78 enlarged the image. Dividing the width or height by the desired size (as in CGImageGetWidth(imageRef) /600, etc.) fixed the problem.

Elise van Looij
  • 4,162
  • 3
  • 29
  • 52

1 Answers1

3

You need one value to be a float to do proper division. Integer division always truncates the floating point numbers. The easiest solution is to turn your numbers into float literals.

CGFloat horizontalRatio = 600.0f / CGImageGetWidth(imageRef);
CGFloat verticalRatio = 600.0f / CGImageGetHeight(imageRef);
CGFloat ratio = MAX(horizontalRatio, verticalRatio);
Joe
  • 56,979
  • 9
  • 128
  • 135
  • Is that what was meant in another post by an f suffix? One learns something everyday. Thanks, I'll accept the answer as soon as I'm allowed to (for some reason one has to wait five minutes). – Elise van Looij Jan 06 '12 at 15:56
  • 1
    Yes, by default 600.0 is a double literal and 600.0f is a float literal. – Joe Jan 06 '12 at 15:58
  • 1
    Bit of an aside, but CGFloat is a double in 64-bit, so there's not much point going forward specifying float in this circumstance... – joerick Jan 07 '12 at 11:34