官方TestCpp有这个demo了,这里还是把它单独拖出来写一下,游戏推广的一个很重要组成就是玩家分享,所以游戏截图就起到很大作用了。截图功能通过CCRenderTexture实现。
1.CCRenderTexture
CCRenderTexture是一个通用渲染对象,可以通过构建一个CCRenderTexture对象,进而把要渲染的东西填充进去,在渲染开始前调用call函数,调用cocos的场景的visit函数对其进行渲染,渲染结束后调用end函数。CCRenderTexture继承于CCNode,所以可以简单地把渲染纹理添加到你的场景中,就像处理其它cocos中的节点一样,当然它还提供了保存功能,可以把渲染纹理保存为PNG或JPG格式。
2.API
-
- static CCRenderTexture * create(int w ,int h, CCTexture2DPixelFormat eFormat, GLuint uDepthStencilFormat);
- static CCRenderTexture * create(int w, int h, CCTexture2DPixelFormat eFormat);
- static CCRenderTexture * create(int w, int h);
- bool initWithWidthAndHeight(int w, int h, CCTexture2DPixelFormat eFormat);
- bool initWithWidthAndHeight(int w, int h, CCTexture2DPixelFormat eFormat, GLuint uDepthStencilFormat);
-
-
- void begin();
-
-
- void beginWithClear(float r, float g, float b, float a);
- void beginWithClear(float r, float g, float b, float a, float depthValue);
- void beginWithClear(float r, float g, float b, float a, float depthValue, int stencilValue);
-
-
- void end();
-
-
- void clear(float r, float g, float b, float a);
- void clearDepth(float depthValue);
- void clearStencil(int stencilValue);
-
-
- bool saveToFile(const char *szFilePath);
- bool saveToFile(const char *name, tCCImageFormat format);
3.示例
修改HelloWorld中结束菜单的回调函数如下:
- void CTestLayer::menuCloseCallback(CCObject* pSender)
- {
- SaveScreenShot();
- }
-
-
- void CTestLayer::SaveScreenShot()
- {
-
- CCSize size = CCDirector::sharedDirector()->getWinSize();
-
- CCRenderTexture* texture = CCRenderTexture::create((int)size.width, (int)size.height);
-
- texture->setPosition(ccp(size.width/2, size.height/2));
-
- texture->begin();
-
- CCDirector::sharedDirector()->getRunningScene()->visit();
-
- texture->end();
-
- texture->saveToFile("screenshot.png", kCCImageFormatPNG);
- }