Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get RGBA color of a specific pixel in CCSprite

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

like image 827
jarektb Avatar asked Dec 09 '22 22:12

jarektb


2 Answers

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.

like image 90
McDevon Avatar answered Dec 19 '22 02:12

McDevon


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];
like image 31
Yannick Loriot Avatar answered Dec 19 '22 01:12

Yannick Loriot