ProgrammingGuide > Advanced Topics > Take a Screenshot

Take a Screenshot

version: Cocos2d-x v3.2-alpha0 and higher
update: Updated about 2 years ago

utils::captureScreen() is added to save a screenshot.

The declaration of utils::captureScreen() is

1
void captureScreen(const std::function<void(bool, const std::string&)>& afterCaptured, const std::string& filename);
  • afterCaptured This function will be called after capturing commands are executed. The boolean return value indicates screenshot is captured successfully or not. The string return value is the path screenshot is saved in.
  • filename The name of screenshot. It can be just a filename, such as screenshot.png. It can also be a resolute path, such as /sdcard/screenshot.png.

The declaration of utils::captureScreen() for Lua is:

1
cc.utils:captureScreen(capturedHandler, filename)
  • capturedHandler This function will be called after capturing commands are executed. The format of the captureHandler as follows:
1
2
3
local function capturedHandler(succeed, outputFile)
           --do something
end

The succeed return value indicates screenshot is captured successfully or not. The string outputFile value is the path screenshot is saved in.

  • filename The name of screenshot. It can be just a filename, such as screenshot.png. It can also be a resolute path, such as /sdcard/screenshot.png.

Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void CaptureScreenTest::afterCaptured(bool succeed, const std::string& outputFile)
{
    if (succeed)
    {
        // show screenshot
        auto sp = Sprite::create(outputFile);
        addChild(sp, 0, childName);
        Size s = Director::getInstance()->getWinSize();
        sp->setPosition(s.width / 2, s.height / 2);
        sp->setScale(0.25);
    }
    else
    {
        log("Capture screen failed.");
    }
}

void CaptureScreenTest::capture()
{
    utils::captureScreen(CC_CALLBACK_2(CaptureScreenTest::afterCaptured, this),"CaptureScreenTest.png");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 local function afterCaptured(succeed, outputFile)
      if succeed then
           local sp = cc.Sprite:create(outputFile)
           layer:addChild(sp, 0, childTag)
           local winSize =  cc.Director:getInstance():getWinSize()
           sp:setPosition(winSize.width / 2, winSize.height / 2)
           sp:setScale(0.25)
      else
           cclog("Capture screen failed.")
      end
end

local function onCaptured(tag, sender)
      cc.Director:getInstance():getTextureCache():removeTextureForKey(fileName)
      layer:removeChildByTag(childTag)
      fileName = "CaptureScreenTest.png"
      cc.utils:captureScreen(afterCaptured, fileName)
end

Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.