【玩转cocos2d-x之三十九】Cocos2d-x 3.0截屏功能集成

3.0的截屏和2.x的截屏基本上同样。都是利用RenderTexture来处理,在渲染之前调用call函数,然后调用Cocos的场景visit函数对其进行渲染,渲染结束后调用end函数就可以。仅仅是3.0截屏须要在截完屏的下一帧才干处理RenderTexture,这点要注意。关于2.x的RenderTexture的API和demo能够參见http://blog.csdn.net/jackystudio/article/details/15498083



本文的重点在于怎样将截图功能继承到Cocos2d-x 3.0引擎。



1.集成到Director

这里选择把截屏功能继承到Director中,让全局的导演来运行截屏功能是一个非常好的主意。


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{
            CCLOG("cocos2d: the image can only be saved as JPG or PNG format");
            return;
        }
    } else {
        CCLOG("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");
}

2.怎样使用saveScreenshot

截屏功能使用起来也非常easy,直接调用saveSecreenshot,当中第一个參数为文件名称(支持png和jpg格式,不带后缀名默觉得png格式),第二个參数为回调函数,你能够在回调函数中处理这个文件。

void ScreenshotTest::saveImage(Ref *pSender){
    static int counter = 0;
     
    char png[20];
    sprintf(png, "image-%d.png", counter);
    char jpg[20];
    sprintf(jpg, "image-%d.jpg", counter);
     
   //截屏后的回调函数,这里显示在左下角
    auto callback = [&](const std::string& fullPath){
        auto sprite = Sprite::create(fullPath);
        CCASSERT(sprite!=nullptr, "Failed to create sprite.");
        addChild(sprite);
        sprite->setScale(0.3f);
        sprite->setPosition(Point(40, 40));
        sprite->setRotation(counter * 3);
        CCLOG("Image saved %s", fullPath.c_str());
    };
     
   //调用Director的截屏功能
    Director::getInstance()->saveScreenshot(png, callback);
    counter++;
}

3.源代码下载

该功能已提交pull request到Cocos2d-x Github上了,有需求的童鞋们能够自己集成了。源代码详细能够參见:https://github.com/cocos2d/cocos2d-x/pull/5978

posted @ 2017-08-02 09:36  cxchanpin  阅读(192)  评论(0编辑  收藏  举报