3.0的截屏和2.x的截屏基本上相同,都是
利用RenderTexture来处理,在渲染之前调用call函数,然后调用Cocos的场景visit函数对其进行渲染,渲染结束后调用end函数即可。只是3.0截屏需要在截完屏的下一帧才能处理RenderTexture,这点要注意。
关于2.x的RenderTexture的API和demo可以参见
http://www.52php.cn/article/p-bomolgql-ep.html
。
本文的重点在于如何将截图功能继承到Cocos2d-x 3.0引擎。
1.集成到Director
这里选择把截屏功能继承到Director中,让全局的导演来执行截屏功能是一个很好的主意。
- voidDirector::saveScreenshot(conststd::string&fileName,conststd::function<void(conststd::string&)>&callback)
- {
- Image::Formatformat;
- if(std::string::npos!=fileName.find_last_of(".")){
- autoextension=fileName.substr(fileName.find_last_of("."),fileName.length());
- if(!extension.compare(".png")){
- format=Image::Format::PNG;
- }elseif(!extension.compare(".jpg")){
- format=Image::Format::JPG;
- }else{
- CCLOG("cocos2d:theimagecanonlybesavedasJPGorPNGformat");
- return;
- }
- }else{
- CCLOG("cocos2d:theimagecanonlybesavedasJPGorPNGformat");
- return;
- }
- autorenderTexture=RenderTexture::create(getWinSize().width,getWinSize().height,Texture2D::PixelFormat::RGBA8888);
- renderTexture->beginWithClear(0.0f,0.0f,0.0f);
- getRunningScene()->visit();
- renderTexture->end();
- renderTexture->saveToFile(fileName,format);
- autofullPath=FileUtils::getInstance()->getWritablePath()+fileName;
- autoscheduleCallback=[&,fullPath,callback](floatdt){
- callback(fullPath);
- };
- auto_schedule=getRunningScene()->getScheduler();
- _schedule->schedule(scheduleCallback,this,false,"screenshot");
- }
2.如何使用saveScreenshot
截屏功能使用起来也很简单,
直接调用saveSecreenshot,其中第一个参数为文件名(支持png和jpg格式,不带后缀名默认为png格式),第二个参数为回调函数,你可以在回调函数中处理这个文件。
- voidScreenshotTest::saveImage(Ref*pSender){
- staticintcounter=0;
- charpng[20];
- sprintf(png,"image-%d.png",counter);
- charjpg[20];
- sprintf(jpg,"image-%d.jpg",counter);
- autocallback=[&](conststd::string&fullPath){
- autosprite=Sprite::create(fullPath);
- CCASSERT(sprite!=nullptr,"Failedtocreatesprite.");
- addChild(sprite);
- sprite->setScale(0.3f);
- sprite->setPosition(Point(40,40));
- sprite->setRotation(counter*3);
- CCLOG("Imagesaved%s",fullPath.c_str());
- };
- Director::getInstance()->saveScreenshot(png,callback);
- counter++;
- }
3.源码下载
该功能已提交pull request到Cocos2d-x Github上了,有需求的童鞋们可以自己集成了。源码具体可以参见:
https://github.com/cocos2d/cocos2d-x/pull/5978 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|