http请求网络图

由 卓别林 创建, 最后一次修改 2016-09-08

本节贴出如何通过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。



以上内容是否对您有帮助:

二维码
建议反馈
二维码