(1)Cocos2d-x 2.x
Cocos2d-x 2.x没有提供截图功能,但是可以用CCRenderTexture来实现这个功能:
- voidCTestLayer::SaveScreenShot()
- {
- //获取屏幕尺寸
- CCSizesize=CCDirector::sharedDirector()->getWinSize();
- //使用屏幕尺寸初始化一个空的渲染纹理对象
- CCRenderTexture*texture=CCRenderTexture::create((int)size.width,(int)size.height);
- //设置位置
- texture->setPosition(ccp(size.width/2,size.height/2));
- //开始获取
- texture->begin();
- //遍历场景节点对象,填充纹理到texure中
- CCDirector::sharedDirector()->getRunningScene()->visit();
- //结束获取
- texture->end();
- //保存为PNG图,Win32/Debug目录下
- texture->saveToFile("screenshot.png",kCCImageFormatPNG);
- }
(2)Cocos2d-x 3.x
在Cocos2d-x 3.2之前,引擎也没有提供截图功能,同样可以使用RenderTexture实现:
- 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{
- log("cocos2d:theimagecanonlybesavedasJPGorPNGformat");
- return;
- }
- }else{
- log("cocos2d:theimagecanonlybesavedasJPGorPNGformat");
- return;
- }
- //获取屏幕尺寸,初始化一个空的渲染纹理对象
- autorenderTexture=RenderTexture::create(getWinSize().width,getWinSize().height,Texture2D::PixelFormat::RGBA8888);
- //清空并开始获取
- renderTexture->beginWithClear(0.0f,0.0f,0.0f);
- //遍历场景节点对象,填充纹理到RenderTexture中
- getRunningScene()->visit();
- //结束获取
- renderTexture->end();
- //保存文件
- renderTexture->saveToFile(fileName,format);
- //使用schedule在下一帧中调用callback函数
- autofullPath=FileUtils::getInstance()->getWritablePath()+fileName;
- autoscheduleCallback=[&,fullPath,callback](floatdt){
- callback(fullPath);
- };
- auto_schedule=getRunningScene()->getScheduler();
- _schedule->schedule(scheduleCallback,this,false,"screenshot");
- }
- voidUtil::captureScreen(conststd::function<void(bool,conststd::string&)>&afterCaptured,conststd::string&filename);