从URL获取图像,在Cocos2dx C ++中使用curl

时间:2013-05-23 13:42:05

标签: c++ curl cocos2d-x

我在C ++中使用curl从Cocos2dx游戏的URL获取图像。 守则工作正常。使用CCImagecocos2d::CCTexture2D我创建了一个Sprite并在我的图层上添加它。

Sprite肯定会被添加到Layer上,(我知道它,因为如果我尝试添加相同的Sprite它就会崩溃说明Child already Added但是它无法在Layer上找到。我试过改变BG颜色,Sprite的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);


    }

}

任何帮助都会受到极大的赞赏。

非常感谢 w ^

1 个答案:

答案 0 :(得分:0)

检查您收到的CURL代码,由于域名限制或因为网址不是来自图片,我在获取图片方面遇到了问题。我从不同的URL测试它,我可以从那里推断出问题。希望这会有所帮助。