How to get screenshot saved path by Cocos2d-x on android

拥有回忆 提交于 2019-12-08 02:17:32

I had the same problem. Apparently, cocos2dx never creates the writable path directory so the screenshot doesn't get saved.

My solution was to, instead of calling CCRenderTexture::saveToFile, copy its implementation and manually save the file to a different path:

std::string MyClass::takeScreenshot(CCScene* scene) {
    cocos2d::CCSize screenSize = cocos2d::CCDirector::sharedDirector()->getWinSize();
    cocos2d::CCRenderTexture* tex = cocos2d::CCRenderTexture::create(screenSize.width, screenSize.height);
    tex->setPosition(ccp(screenSize.width/2, screenSize.height/2));

    //use a different dir than cocos default writable path
    std::string filename = "/sdcard/Android/data/screenshot.png";

    tex->begin();
    scene->getParent()->visit();
    cocos2d::CCImage* img = tex->newCCImage(true);
    img->saveToFile(filename.c_str(), true);
    CC_SAFE_DELETE(img);
    tex->end();

    return filename;
}
alc77

I also had the same problem. When I try renderTexture->saveToFile method, I can't submit path to java. No matter, I used getWritablePath() or set the path directly "/sdcard/Android/data/com.xxx.xxx/snapshot.jpg".
I try also to solve this problem on the advice of Facundo Olano. But CCImage compose only solid black image.
Finally I combine this two methods. First, I make an image by renderTexture->saveToFile:

void MyScene::pressFaceBook()
{
    ...
    RenderTexture* renderTexture = RenderTexture::create(sharedImage->getBoundingBox().size.width, sharedImage->getBoundingBox().size.height, Texture2D::PixelFormat::RGBA8888);
    renderTexture->begin();
    sharedImage->visit();
    renderTexture->end();
    renderTexture->saveToFile("snapshot.jpg", Image::Format::JPG);
    const std::string fullpath = FileUtils::getInstance()->getWritablePath() + "snapshot.jpg";
    sharedImage->setVisible(false);
    this->runAction(Sequence::create(DelayTime::create(2.0f),
                                     CallFunc::create(std::bind(&MyScene::shareFaceBook, this, fullpath)),
                                     NULL));
}

And then I use initWithImageFile with the transferred file name:

void MyScene::shareFaceBook(const std::string& outputFile)
{
    const std::string joutputFile = "/sdcard/Android/data/com.xxx.xxx/snapshot.jpg";
    cocos2d::Image* img = new Image;
    img->initWithImageFile(fullpath);
    img->saveToFile(joutputFile);
    CC_SAFE_DELETE(img);
    singleton->shareFaceBook(joutputFile);
}

A delay of 2 seconds is needed to capture the screenshot. Of course, instead com.xxx.xxx you must substitute your app name.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!