Cocos2d-x 2.x
Cocos2d-x 2. x does not provide functionality, but it can be achieved with ccrendertexture:
Void ctestlayer: savescreenshot () {// obtain the screen size ccsize size = ccctor ctor: shareddire()-> getwinsize (); // use the screen size to initialize an empty rendered texture object: ccrendertexture * texture = ccrendertexture: Create (INT) size. width, (INT) size. height); // set the position texture-> setposition (CCP (size. width/2, size. height/2); // start to get texture-> begin (); // traverse the scene Node object and fill the texture into the texure ccdirector: shareddirector ()-> getrunningscene () -> visit (); // obtain the texture end-> end (); // save it as a PNG image. In the Win32/DEBUG directory, texture-> savetofile ("screenshot.png ", kccimageformatpng );}
(2) Cocos2d-x 3.x
Before Cocos2d-x 3.2, the engine did not provide functionality and can also be implemented using rendertexture:
Void Director: savescreenshot (const STD: string & filename, const STD: function <void (const STD: string &)> & callback) {image: format; // determine the suffix 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 ;}// get the screen size, initialize an empty rendering texture object auto rendertexture = rendertexture: Create (getwinsize (). width, getwinsize (). height, texture2d: pixelformat: rgba8888); // clear and start obtaining rendertexture-> beginwithclear (0.0f, 0.0f, 0.0f, 0.0f); // traverse scene node objects, fill in the texture to the rendertexture getrunningscene ()-> visit (); // get the rendertexture-> end (); // save the file rendertexture-> savetofile (filename, format ); // call the callback function 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 ");}
(3) Since Cocos2d-x 3.2, the engine provides the capturescreen function to achieve the function:
void Util::captureScreen(const std::function<void(bool, const std::string&)>& afterCaptured, const std::string& filename);
Cocos2d-x Functions