【问题标题】:Save sprite content as .png file with cocos2d-x使用 cocos2d-x 将精灵内容保存为 .png 文件
【发布时间】:2023-04-27 18:29:02
【问题描述】:

我需要创建一个空精灵作为容器,并在不同位置添加使用不同图像创建的不同精灵。最后,我需要将作为子元素添加到容器精灵中的结果保存为图像 - 例如 .png。

我该怎么做?

【问题讨论】:

    标签: c++ cocos2d-x cocos2d-x-3.0


    【解决方案1】:

    您可以使用 RenderTexture 和调用 Sprite 的访问方法。这是一个示例代码:

    RenderTexture* renderTexture = RenderTexture::create(width, height, Texture2D::PixelFormat::RGBA8888);
    renderTexture->begin();
    sprite->visit();
    renderTexture->end();
    renderTexture->saveToFile("snapshot.png", Image::Format::PNG);
    

    【讨论】:

    • 谢谢维卡斯 :)。你能解释一下visit是做什么的吗?
    • CCNode::visit() 将导致儿童的递归绘制,以便RenderTexture 可以抓住它。您需要访问您要捕获的所有节点,否则它将保存黑色PNG图像。
    • 我在安卓上用过这段代码,找不到图片。我打印了FileUtils::getInstance()->getWritablePath(),它等于/data/data/com.test.cakepop/files/。我以为文件可能在那里,但 Astro 文件管理器说 /data 是空的。
    • 我在 iOS 上对其进行了测试,在 init() 方法中运行良好,但在 Windows 上无法运行。它仅在 onEnter() 方法内工作。在这里检查线程:discuss.cocos2d-x.org/t/…
    • 它适用于Android,它写入getWriteablePath。我只是看不到或找不到它。我是否需要设备上的超级用户才能查看/data/data/com.test.cakepop/files/
    最近更新 更多