游戏推广的一个很重要组成就是玩家分享,所以游戏截图就起到很大作用了。截图功能通过CCRenderTexture实现。
1.CCRenderTexture
CCRenderTexture是一个通用渲染对象,可以通过构建一个CCRenderTexture对象,把要渲染的东西填充进去,在渲染开始前调用call函数,调用cocos的场景的visit函数对其进行渲染,渲染结束后调用end函数。
CCRenderTexture继承于CCNode,所以可以简单地把渲染纹理添加到你的场景中,就像处理其它cocos中的节点一样,当然它还提供了保存功能,可以把渲染纹理保存为PNG或JPG格式。
在实际应用中中,只是获取渲染的纹理还不够,还要考虑不同尺寸设备的截图范围,当然,这个是针对采用kResolutionNoBorder屏幕适配方案来说,下面的粒子就是针对kResolutionNoBorder。
2.API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //创建和初始化函数 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); //保存纹理为图片文件,可以选择JPG/PNG格式,默认是JPEG格式,成功返回真 bool saveToFile( const char *szFilePath); bool saveToFile( const char *name, tCCImageFormat format); |
3.示例
修改HelloWorld中结束菜单的回调函数如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | void CTestLayer::menuCloseCallback(CCObject* pSender) { SaveScreenShot(); } //截图功能 void CTestLayer::SaveScreenShot() { //获取屏幕尺寸 //CCDirector::sharedDirector()->getVisibleSize(); CCSize size = CCDirector::sharedDirector()->getWinSize(); CCPoint origin = VisibleRect::getVisibleRect().origin; CCSize visableSize = VisibleRect::getVisibleRect().size; //使用屏幕尺寸初始化一个空的渲染纹理对象 CCRenderTexture* texture = CCRenderTexture::create(( int )size.width, ( int )size.height); //设置位置 texture->setPosition(ccp(size.width/2, size.height/2)); CCScene* curScene = CCDirector::sharedDirector()->getRunningScene(); //开始获取 texture->begin(); //遍历场景节点对象,填充纹理到texure中 curScene->visit(); //结束获取 texture->end(); //保存为PNG图 if (origin.x == 0 && origin.y == 0) { texture->saveToFile( "screenshot.png" , kCCImageFormatPNG); return ; } // 适配不同尺寸设备,只截取屏幕大小的尺寸,没采用kResolutionNoBorder就不用下面的处理 CCRect finalRect = CCRectMake(origin.x, origin.y, visableSize.width, visableSize.height); CCSprite *sprite = CCSprite::createWithTexture(texture->getSprite()->getTexture(), finalRect); sprite->setAnchorPoint(CCPoint(0, 0)); sprite->setFlipY( true ); CCRenderTexture *finalRtx = CCRenderTexture::create(visableSize.width, visableSize.height); finalRtx->begin(); sprite->visit(); finalRtx->end(); finalRtx->saveToFile( "screenshot.png" , kCCImageFormatPNG); } |