android - 如何使用 url 创建 Sprite?

标签 android c++ cocos2d-x

我正在使用 cocos2dx v3.0 开发跨平台应用程序(iOS、Android)。我想用 URL 创建一个 CCSprite。我认为没有 cocos 方法可以做到这一点,所以我必须为 Android 和 iOS fork 我的代码。

最佳答案

You have to Http request the image url and once you got the response, you can create image from that response data and save it to your phone. After that you can create the sprite from the save image.

    void ClassName::downLoadImage()
    {
            std::string strImage = "img.png";

            CCHttpRequest* request = new CCHttpRequest();
            request->setUrl("url of your image");
            request->setRequestType(CCHttpRequest::kHttpGet);
            request->setResponseCallback(this, httpresponse_selector(ClassName::onImageDownLoaded));
            request->setTag(strImage.c_str());
            CCHttpClient::getInstance()->send(request);
            request->release();
    }

    void ClassName::onImageDownLoaded(CCHttpClient* pSender, CCHttpResponse* pResponse)
    {
        CCHttpResponse* response = pResponse;

        if (!response)
        {
            CCLog("No Response");
            return;
        }
        int statusCode = response->getResponseCode();

        char statusString[64] = {};
        sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
        CCLog("response code: %d", statusCode);

        if (!response->isSucceed())
        {
            CCLog("response failed");
            CCLog("error buffer: %s", response->getErrorBuffer());
            return;
        }
        std::vector<char> *buffer = response->getResponseData();

        CCImage * img=new CCImage();
        img->initWithImageData(&(buffer->front()), buffer->size());

        // Save image file to device.
        std::string writablePath = CCFileUtils::sharedFileUtils()->getWritablePath();
        writablePath.append(response->getHttpRequest()->getTag());


         //Now create Sprite from downloaded image
         CCSprite* pSprite = CCSprite::create(writablePath.c_str());
         addchild(pSprite);
    }

关于android - 如何使用 url 创建 Sprite?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28171458/

相关文章:

cocos2d-x - 在代码块中找不到 fontconfig/fontconfig.h

android - onBackPressed 移除@Override注解

c++ - 包含来自其他项目的 stdafx.h

c++ - 具有多个参数的模板的 Qt foreach

c++ - 从 std::vector 创建 tensorflow::tensor 的最有效方法

cocos2d-x - 适用于cocos2dx游戏的iPhone X/三星Galaxy S8长宽比问题

cocos2d-x - 更改播放器动画时出错

android - 如何在主 Activity 之前获得登录 Activity

android - 在 aws devicefarm 中为一组特定的 android 手机创 build 备池

android - Android OpenGL是否有drawbitmap性能的离屏功能