首页 > 代码库 > Cocos2d-x3.1及3.2实现截屏功能

Cocos2d-x3.1及3.2实现截屏功能

1、Cocos2d-x3.1

在Cocos2d-x3.2之前,Cocos引擎没有提供截图功能,但是可以通过RenderTexture实现,

1.1首先在CCDirector.h中添加如下代码:并在其中添加头文件  #include"2d/CCRenderTexture.h"

    void saveScreenshot(const std::string& fileName,const std::function<void(const std::string&)>& callback);

1.2然后在CCDirector.cpp中添加如下代码:

void Director::saveScreenshot(const std::string &fileName, const std::function<void (const std::string &)> &callback)
{
    Image::Format format;
    //进行后缀判断
    if(std::string::npos != fileName.find_last_of(".")){
        auto extension = fileName.substr(fileName.find_last_of("."),fileName.length());
        if (!extension.compare(".png")) {
            format = Image::Format::PNG;
        } else if(!extension.compare(".jpg")) {
            format = Image::Format::JPG;
        } else{
            log("cocos2d: the image can only be saved as JPG or PNG format");
            return;
        }
    } else {
        log("cocos2d: the image can only be saved as JPG or PNG format");
        return ;
    }
    //获取屏幕尺寸,初始化一个空的渲染纹理对象
    auto renderTexture = RenderTexture::create(getWinSize().width, getWinSize().height, Texture2D::PixelFormat::RGBA8888);
    //清空并开始获取
    renderTexture->beginWithClear(0.0f, 0.0f, 0.0f, 0.0f);
    //遍历场景节点对象,填充纹理到RenderTexture中
    getRunningScene()->visit();
    //结束获取
    renderTexture->end();
    //保存文件
    renderTexture->saveToFile(fileName , format);
    //使用schedule在下一帧中调用callback函数
    auto fullPath = FileUtils::getInstance()->getWritablePath() + fileName;
    auto scheduleCallback = [&,fullPath,callback](float dt){
        callback(fullPath);
    };
    auto _schedule = getRunningScene()->getScheduler();
    _schedule->schedule(scheduleCallback, this, 0.0f,0,0.0f, false, "screenshot");

}

1.3在HelloWorld.cpp中添加如下代码:

bool HelloWorld::init()
{
    bool bRet = false;
    do{
        CC_BREAK_IF(!Layout::init());
        auto button = ui::Button::create("CloseNormal.png","CloseSelected.png");
        button->setPosition(Vec2(200,200));
        addChild(button);
        button->addTouchEventListener(CC_CALLBACK_2(HomeLayer::touchEvent,this));
        Director::getInstance()->getEventDispatcher();
        
        bRet = true;
    }while(0);
    return bRet;
}

void 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", [&](const std::string &str){
                log("str = %s",str.c_str());
            });
            break;
        default:
            break;
    }
}

1.4点击按钮,实现截图功能,最后图片保存在沙盒中,可在Xcode控制台下看到文件保存路径。

2、Cocos2d-x3.2

Cocos2d-x3.2中已经封装了截图共,使用如下
void Util::captureScreen(const std::function<void(bool, const std::string&)>& afterCaptured, const std::string& filename);

Cocos2d-x3.1及3.2实现截屏功能