我在 C++ 中使用 curl 从 Cocos2dx 游戏的 URL 中获取图像。代码运行良好。并使用CCImage
我cocos2d::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);
}
}
任何帮助将不胜感激。
非常感谢