原文链接:http://www.it165.net/pro/html/201409/21451.html
1.1首先在CCDirector.h中添加如下代码:并在其中添加头文件 #include "2d/CCRenderTexture.h"
1.
void
saveScreenshot(
const
std::string& fileName,
std::function<
(
std::string&)>& callback);
1.2然后在CCDirector.cpp中添加如下代码:
01.
Director::saveScreenshot(std::string &fileName,宋体; background:none">std::string &)> &callback)
02.
{
03.
Image::Format format;
04.
05.
if
(std::string::npos != fileName.find_last_of(
"."
)){
06.
auto extension = fileName.substr(fileName.find_last_of(
),fileName.length());
07.
(!extension.compare(
".png"
)) {
08.
format = Image::Format::PNG;
09.
}
else
".jpg"
10.
format = Image::Format::JPG;
11.
else{
12.
log("cocos2d: the image can only be saved as JPG or PNG format"
);
13.
return
;
14.
}
15.
16.
17.
18.
19.
20.
auto renderTexture = RenderTexture::create(getWinSize().width,getWinSize().height,Texture2D::PixelFormat::RGBA8888);
21.
//清空并开始获取
22.
renderTexture->beginWithClear(0
.0f,
.0f);
23.
//遍历场景节点对象,填充纹理到RenderTexture中
24.
getRunningScene()->visit();
25.
//结束获取
26.
renderTexture->end();
27.
//保存文件
28.
renderTexture->saveToFile(fileName,format);
29.
//使用schedule在下一帧中调用callback函数
30.
auto fullPath = FileUtils::getInstance()->getWritablePath() + fileName;
31.
auto scheduleCallback = [&,fullPath,callback](float
dt){
32.
callback(fullPath);
33.
};
34.
auto _schedule = getRunningScene()->getScheduler();
35.
_schedule->schedule(scheduleCallback,宋体; background:none">this,宋体; background:none">false
"screenshot"
);
36.
37.
}
1.3在HelloWorld.cpp中添加如下代码:
bool HelloWorld::init()
bool bRet =
do
CC_BREAK_IF(!Layout::init());
auto button = ui::Button::create(
"CloseNormal.png"
"CloseSelected.png"
button->setPosition(Vec2(
200
));
addChild(button);
button->addTouchEventListener(CC_CALLBACK_2(HomeLayer::touchEvent,宋体; background:none">Director::getInstance()->getEventDispatcher();
bRet =
true
;
while
(
bRet;
}
HelloWorld::touchEvent(cocos2d::Ref *pSender,cocos2d::ui::Widget::TouchEventType type)
switch
(type)
case
Widget::TouchEventType::ENDED:
<span style=
"white-space:pre"
> </span>
Director::getInstance()->saveScreenshot(
"homeLayer.png"
std::string &str){
"str = %s"
});
break
default
:
}
1.4点击按钮,实现截图功能,最后图片保存在沙盒中,可在Xcode控制台下看到文件保存路径。
2、Cocos2d-x3.2
Cocos2d-x3.2中已经封装了截图共,使用如下
Util::captureScreen((bool,宋体; background:none">std::string&)>&afterCaptured,宋体; background:none">std::string&filename);