Frage

I have the following code on Mac OSX to load an image:

NSImage *baseImage = [NSImage imageNamed:[NSString stringWithCString:file.getFilename().c_str() encoding:NSUTF8StringEncoding]];

And the following code on iOS to load an image:

UIImage* baseImage = [UIImage imageNamed:[NSString stringWithCString:file.getFilename().c_str() encoding:NSUTF8StringEncoding]];

And the following line on both platforms after the image load:

printf("Surface: \"%s\" size: %d, %d\n", file.getFilename().c_str(), (int)[baseImage size].width, (int)[baseImage size].height);

If the image in question is 72 DPI, then on both platforms, I get this as output:

Surface: "player.png" size: 30, 30 (Mac)
Surface: "player.png" size: 30, 30 (iOS)

However, if the image is 96 DPI, then I get different results:

Surface: "player.png" size: 30, 30 (Mac)
Surface: "player.png" size: 40, 40 (iOS)

Although it's odd behavior that Mac scales the image to match 72 DPI and iOS doesn't scale it, I would like to get consistent results across platforms. (Preferably scaling down to 72 DPI.)

tl;dr: On iOS, how can I detect the DPI of the image and scale it accordingly?

War es hilfreich?

Lösung

An NSImage instance can actually contain more than one representation of an image (which are instances of NSImageRep), and may have different sizes. You should understand "size" to mean size in drawing unit points, not pixel dimensions.

If you want the pixel dimensions, get an NSImageRep at the size you are interested in with -bestRepresentationForRect:context:hints:, then call -pixelsHigh and -pixelsWide.

The PNG format may contain fields that describe the actual size of the image, and it would appear NSImage is honoring that, and perhaps UIImage is not.

You can inspect your image files (png's) using the "sips" command line tool (type "man sips" for more info). It has options to read and manipulate both the pixel dimensions and DPI of a wide variety of image formats.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top