-
1、Cocos2d-x3.1
在Cocos2d-x3.2之前,Cocos引擎没有提供截图功能,但是可以通过RenderTexture实现, - 原文链接:http://www.it165.net/pro/html/201409/21451.html
1.1首先在CCDirector.h中添加如下代码:并在其中添加头文件 #include "2d/CCRenderTexture.h"
1.
void
saveScreenshot(
const
std::string& fileName,
const
std::function<
void
(
const
std::string&)>& callback);
1.2然后在CCDirector.cpp中添加如下代码:
01.
void
Director::saveScreenshot(
const
std::string &fileName,
const
std::function<
void
(
const
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.
if
(!extension.compare(
".png"
)) {
08.
format = Image::Format::PNG;
09.
}
else
if
(!extension.compare(
".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.
}
else
{
16.
log(
"cocos2d: the image can only be saved as JPG or PNG format"
);
17.
return
;
18.
}
19.
//获取屏幕尺寸,初始化一个空的渲染纹理对象
20.
auto renderTexture = RenderTexture::create(getWinSize().width, getWinSize().height, Texture2D::PixelFormat::RGBA8888);
21.
//清空并开始获取
22.
renderTexture->beginWithClear(
0
.0f,
0
.0f,
0
.0f,
0
.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,
this
,
0
.0f,
0
,
0
.0f,
false
,
"screenshot"
);
36.
37.
}
1.3在HelloWorld.cpp中添加如下代码:
01.
bool HelloWorld::init()
02.
{
03.
bool bRet =
false
;
04.
do
{
05.
CC_BREAK_IF(!Layout::init());
06.
auto button = ui::Button::create(
"CloseNormal.png"
,
"CloseSelected.png"
);
07.
button->setPosition(Vec2(
200
,
200
));
08.
addChild(button);
09.
button->addTouchEventListener(CC_CALLBACK_2(HomeLayer::touchEvent,
this
));
10.
Director::getInstance()->getEventDispatcher();
11.
12.
bRet =
true
;
13.
}
while
(
0
);
14.
return
bRet;
15.
}
16.
17.
void
HelloWorld::touchEvent(cocos2d::Ref *pSender, cocos2d::ui::Widget::TouchEventType type)
18.
{
19.
switch
(type)
20.
{
21.
case
Widget::TouchEventType::ENDED:
22.
<span style=
"white-space:pre"
> </span>
//参数依次为保存图片的名字,在控制台打印保存路径信息
23.
Director::getInstance()->saveScreenshot(
"homeLayer.png"
, [&](
const
std::string &str){
24.
log(
"str = %s"
,str.c_str());
25.
});
26.
break
;
27.
default
:
28.
break
;
29.
}
30.
}
1.4点击按钮,实现截图功能,最后图片保存在沙盒中,可在Xcode控制台下看到文件保存路径。
2、Cocos2d-x3.2
Cocos2d-x3.2中已经封装了截图共,使用如下1.
void
Util::captureScreen(
const
std::function<
void
(bool,
const
std::string&)>& afterCaptured,
const
std::string& filename);
-
Cocos2d-x3.1及3.2实现截屏功能
最新推荐文章于 2021-11-01 10:57:42 发布