Reputation: 4215
I have more experience with Cocos2D than UIKit. One of the challenges in Cocos2D is the amount of memory which can be used by CCSprite. This amount is not affected by the size of the image file on disk - instead it is based on the image's dimensions and the pixel format used. It is therefore not affected by optimisations made to the image file, although these may allow a cheaper pixel format to be used.
In iOS development, is there a way to have a displayed image only take up as much memory as the size of the file on disk, and no more - and is that how UIImageView works in UIKit?
Upvotes: 1
Views: 686
Reputation: 64477
No and no.
It bears repeating: the size of an image file on disk can not be compared to the size of the image in memory as a texture.
For example, a PNG file uses a losless compression whereas the same image as a JPG file uses lossy compression and therefore can be significantly smaller. But once loaded as a texture, both textures will use the same amount of memory because the GPU doesn't know what a PNG or JPG is, it can only work with the various texture formats the GPU supports and those formats don't happen to be any of the common image file formats because they serve very different purposes.
Every image that should be displayed on screen needs to be loaded into a texture. Texture sizes are defined by a few properties: size, color & alpha bith depth, and where supported: compression.
As for compression, the only supported formats on iOS devices are PVRTC2 and PVRTC4 (the 2 and 4 stand for 2-Bit and 4-Bit but that's not comparable to actual color bit depth). Textures using this format use very little memory and render very fast, but you lose image quality and color vibrancy, in many cases just too much to be acceptable.
That leaves you with the uncompressed formats, which are either 8-Bit, 16-Bit or 32-Bit textures. 8-Bit textures are only used for masking, tinting and other technical uses, they are essentially greyscale images.
The gist of textures used in games and apps are either 16-Bit or 32-Bit. Meaning that per pixel in the texture you need either 2 Bytes or 4 Bytes of memory. A 1024x1024 texture with 32-Bit color-depth uses 1024x1024x4 = 4,194,304 Bytes or 4 Megabytes of memory, regardless of the image file size.
Usually developers strive to use 16-Bit textures since that halves the memory usage and gives a slight performance boost. Unless the images uses gradients where the missing extra colors can become noticeable. For large images or fast-moving images PVR images can improve rendering performance and memory usage, but should only be used where the difference to uncompressed textures is hardly noticeable.
Finally, UIImageView is not optimized for rendering speed, not in the least bit. If you plan to make a game based on UIImageView, you could as well shoot yourself in the foot - you'd actually save yourself some pain that way. :)
Upvotes: 3