本节贴出如何通过http请求网络图片,并绘制到屏幕上
发送请求
/**
编译到Android平台之后注意添加联网权限
**/
CCHttpRequest* request = new CCHttpRequest();
// 请求图片的url
request->setUrl("http://www.9miao.com/template/dean_hotspot_141011/deancss/logo.png");
//请求方式
request->setRequestType(CCHttpRequest::kHttpGet);
//设置回调
request->setResponseCallback(this, httpresponse_selector(FirstViewController::onHttpRequestImageCompleted));
// 设置tag
request->setTag("image");
CCHttpClient::getInstance()->send(request);
request->release();
接受图片
void FirstViewController::onHttpRequestImageCompleted(CCHttpClient *sender, CCHttpResponse *response)
{
if (!response)
{
return;
}
if (!response->isSucceed())
{
CCLog("response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
return;
}
vector<char> *buffer = response->getResponseData();
//创建一个CCImage
CCImage* img = new CCImage();
img->initWithImageData((unsigned char*)buffer->data(), buffer->size());
//创建一个纹理CAImage
CAImage* texture = new CAImage();
bool isImg = texture->initWithImage(img);
img->release();
//通过CAImageView绘制到屏幕
CAImageView* iv = CAImageView::createWithImage(texture);
iv->setFrame(DRect(0, 0, 200, 200));
this->getView()->addSubview(iv);
}
如果成功,将会看到9秒社团的logo。
(c) 2024 chaojicainiao.com MIT license