如何在CCSprite中获取特定像素的RGBA颜色

jar*_*ktb 4 iphone objective-c cocos2d-iphone ccsprite

我正在使用cocos2d为iPhone v1.0.1库为iPhone编写游戏.为了让我的游戏工作正常,我需要在知道坐标时检查CCSprite中特定像素的颜色.我一直在寻找解决方案两天,但我没有找到任何工作.也许有人之前做过这件事并且知道该怎么做?

对我来说另一个可能性是如果这更容易从CCSprite创建一个UIImage ...

问候,jarektb

小智 10

显然,无法直接访问包含精灵的颜色缓冲区.但是,您可以将精灵绘制到CCRenderTexture并从那里读取像素.

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]);
Run Code Online (Sandbox Code Playgroud)

如果您使用的是视网膜显示器,则必须考虑内容比例因子.

该解决方案还可以轻松转换为CCSprite类别或子类.

这似乎是一个老话题,但我在这里发布了答案,因为这是谷歌刚刚遇到同样困境时的第一次打击.