Question

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.

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top