One of the challenges faced when developing applicationf for the iPhone and iPad is the memory limitation.  These devices understandably have much less memory than a computer, so careful memory consumption is essential.

cocos2d version introduces several improvements, and one of them is the ability to select the color-depth for sprites.  This is a good improvement as it allows developers to use memory more efficiently and in many cases fits more graphics (albeit with lower quality) into the applications.

Color depth can be set using this function:

@implementation Texture2D (PixelFormat)
+(void) setDefaultAlphaPixelFormat:(Texture2DPixelFormat)format
	defaultAlphaPixelFormat = format;

The Texture2DPixelFormat values are defined in Texture2D.h, shown below:

/** Possible texture pixel formats */
typedef enum {
	kTexture2DPixelFormat_Automatic = 0,
	//! 32-bit texture: RGBA8888
	//! 16-bit texture: used with images that have alpha pre-multiplied
	//! 8-bit textures used as masks
	//! 16-bit textures: RGBA4444
	//! 16-bit textures: RGB5A1
} Texture2DPixelFormat;


You should set the color depth before calling any Texture2D functions, like during initialization. For example in applicationDidFinishLaunching:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Init the window
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

// cocos2d will inherit these values
[window setUserInteractionEnabled:YES];
[window setMultipleTouchEnabled:NO];
[Texture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA4444];


Memory Usage.

The lower number of bits, the lower memory consumption, using Instruments, here’s a memory usage comparison of a sprite 480×300 in dimension.



Since iPhone and iPad have limited number of memory, it is a good idea to experiment with this option is you find yourself running out of memory.

Image Quality

As you can see, the lower color-depth uses less memory because less number of bytes are used per pixel.  The quality degradation may or may not be important to you.  If you are developing games consisting of mostly two-dimensional cartoon images, then the difference may not even be noticeable.  Images with gradients usually have more noticeable differences.  To illustrate a rather extreme cases, here’s the comparison:




Notice the “steps” or banding in the kTexture2DPixelFormat_RGBA4444 version.  However, this is an extreme example and most 2D graphics does not suffer that much degradation.

More example can be found in this post:

One Response to “Cocos2d for iPhone: Color Depth and Memory Optimizations”

  1. [...] Cocos2d for iPhone: Color Depth and Memory Optimizations [...]