I am writing a game for iPhone using the cocos2d for iPhone v1.0.1 library. To get my game work fine I need to check the color of a specific pixel in a CCSprite when i know the coordinates. I have been looking for the solution for two days but I did not find any working. Maybe someone did this before and knows how to do it?
Another posibility for me would be creating an UIImage from CCSprite if this is easier...
greetings, jarektb
Appearantely the color buffer containing the sprite cannot be directly accessed. However, you can draw the sprite to a CCRenderTexture and read the pixel from there.
location = ccp(x * CC_CONTENT_SCALE_FACTOR(), y * CC_CONTENT_SCALE_FACTOR());
UInt8 data[4];
CCRenderTexture* renderTexture = [[CCRenderTexture alloc] initWithWidth:sprite.boundingBox.size.width * CC_CONTENT_SCALE_FACTOR()
height:sprite.boundingBox.size.height * CC_CONTENT_SCALE_FACTOR()
pixelFormat:kCCTexture2DPixelFormat_RGBA8888];
[renderTexture begin];
[sprite draw];
glReadPixels((GLint)location.x,(GLint)location.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, data);
[renderTexture end];
[renderTexture release];
NSLog(@"R: %d, G: %d, B: %d, A: %d", data[0], data[1], data[2], data[3]);
If you are using a retina display, you have to take the content scale factor into account.
The solution can also easily be turned into a CCSprite category or subclass.
This seems to be an old topic, but I posted the answer here as this was the first hit on google when I was having the same dilemma just now.
If your sprite is visible on the screen, you can use the glReadPixels function. It should look like this (where x
and y
on the second line are the coordinates):
ccColor4B *buffer = malloc(sizeof(ccColor4B));
glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
ccColor4B color = buffer[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With