【玩轉cocos2d-x之三十九】Cocos2d-x 3.0截圖功能整合
阿新 • • 發佈:2019-01-01
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
截圖功能使用起來也很簡單,直接呼叫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++; }