cocos2dx之保存截屏图片

时间:2022-09-29 22:16:50

http://blog.****.net/ganpengjin1/article/details/19088921

我们要保存当前的运行的scene的截图的话,我用到CCRenderTexture,看例子代码:

  1. CCSize size = CCDirector::sharedDirector()->getWinSize();
  2. CCRenderTexture *screen = CCRenderTexture::create(size.width, size.height);
  3. CCScene *scene = CCDirector::sharedDirector()->getRunningScene();
  4. screen->begin();
  5. scene->visit();//将当前的整个scene绘出来
  6. screen->end();
  7. screen->saveToFile("MyCurScene.png", kCCImageFormatPNG);

然后我们再看后面的saveToFile源码:

  1. bool CCRenderTexture::saveToFile(const char *fileName, tCCImageFormat format)
  2. {
  3. bool bRet = false;
  4. CCAssert(format == kCCImageFormatJPEG || format == kCCImageFormatPNG,
  5. "the image can only be saved as JPG or PNG format");
  6. CCImage *pImage = newCCImage(true);
  7. if (pImage)
  8. {
  9. std::string fullpath = CCFileUtils::sharedFileUtils()->getWritablePath() + fileName;//得到保存资源的位置
  10. bRet = pImage->saveToFile(fullpath.c_str(), true);
  11. }
  12. CC_SAFE_DELETE(pImage);
  13. return bRet;
  14. }

对于传进来的fileName,内部又调用了下面的函数,通过getWritablePath提供了存储的路径,getWritablePath内部通过不同平台提供不同的路径,于是对于常见的两种平台,有了下面的路径。

  1. std::string fullpath = CCFileUtils::sharedFileUtils()->getWritablePath() + fileName;

a.如果是VS环境下的话,会存放在跟项目相关的Debug.win32目录下;

b.如果是在Android平台下,会存放在类似这样的一个路径下面/data/data/com.nt.tower/files/cocos2d-x-screenshot.png(这个是我的安卓工程拿到的路径)

这个路径才是我们更关心的,结构类似于这样 /data/data/+PACKAGE+/files/filename(package就是安卓工程的主包名,一般都是com.xx.yy这种)

它的第二个参数是cocos2dx所支持的图片格式:

    1. typedef enum eImageFormat
    2. {
    3. kCCImageFormatJPEG      = 0,
    4. kCCImageFormatPNG       = 1,
    5. } tCCImageFormat;