0

我在 C++ 中使用 curl 从 Cocos2dx 游戏的 URL 中获取图像。代码运行良好。并使用CCImagecocos2d::CCTexture2D创建一个Sprite并将其添加到我的图层上。

精灵肯定会添加到图层上,(我知道是因为如果我尝试添加相同的精灵,它会崩溃状态Child already Added但它在图层上找不到。我尝试更改背景颜色,精灵的 ZIndex 但是精灵不可见。

这是代码:

void HelloWorld::getImageFromURL(const char* url)
{
    CURL *curl;       // CURL objects
    CURLcode res;
    MemoryStruct buffer; // memory buffer

    curl = curl_easy_init(); // init CURL library object/structure

    if(curl) {

        // set up the write to memory buffer
        // (buffer starts off empty)

        buffer.memory = NULL;
        buffer.size = 0;

        stringstream urlString;
        urlString<<url;
        // (N.B. check this URL still works in browser in case image has moved)

        CCLog("%s", urlString.str().c_str());

        curl_easy_setopt(curl, CURLOPT_URL, urlString.str().c_str());
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); // tell us what is happening

        // tell libcurl where to write the image (to a dynamic memory buffer)

        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION, Utility::WriteMemoryCallback);
        curl_easy_setopt(curl,CURLOPT_WRITEDATA, (void *) &buffer);

        // get the image from the specified URL

        res = curl_easy_perform(curl);
        CCLog("Curl code: %i", res);

        CCImage* img = new CCImage();
        img->initWithImageData((void*)buffer.memory, (long)buffer.size, CCImage::kFmtPng);
        cocos2d::CCTexture2D* texture = new cocos2d::CCTexture2D(); //TODO:: leak
        texture->initWithImage(img);


        CCSprite* sprite = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 256, 256));
        sprite->setPosition(CENTRE_OF_SCREEN);
        sprite->setContentSize(CCSize(256,256));
        sprite->setAnchorPoint(ccp(0, 0));
        this->addChild(sprite,1000,1000);

        curl_easy_cleanup(curl);
        free(buffer.memory);


    }

}

任何帮助将不胜感激。

非常感谢

4

1 回答 1

0

检查您收到的 CURL 代码,由于域限制或 URL 不是来自图像,我在获取图像时遇到问题。我从不同的 URL 对其进行了测试,我可以从那里推断出问题所在。希望这可以帮助。

于 2014-03-03T19:10:11.070 回答