Cocos2d-x利用CCHttpRequest获取网络图片并显示
利用CCHttpRequest获取网上http地址的图片并缓存到本地生成CCSprite用于显示
//图片结构
class imgstruct : public CCObject
{
public:
imgstruct(const char* iName, const char* idStr, CCLayer* _layer, bool mask)
{
imageName = string(iName);
observerId = string(idStr);
layer = _layer;
useMask = mask;
}
~imgstruct()
{
} string imageName;
string observerId;
CCLayer* layer; //父layer
bool useMask;
};
//图片监听,下载完成触发
class CCImageNotificationCenter : public CCNotificationCenter
{
public:
DECLARE_SINGLETON_CLASS(CCImageNotificationCenter);
CCImageNotificationCenter();
~CCImageNotificationCenter(); CCString addObserver(const char *imageName,CCLayer* layer,bool useMask);
void imageLoaded();
void removeObserver(const char *name); void postNotification(const char *name, CCObject *object); void imageLoaded(CCObject *obj);
static CCSprite* getSpriteFromWriteablePath(const char* name); private:
CCNotificationCenter m_notificationCenter;
int m_observerID;
};
具体实现
CCString CCImageNotificationCenter::addObserver(const char *imageName, CCLayer* layer, bool useMask)
{
CCString* observerIDstr = CCString::createWithFormat("%d",m_observerID); m_notificationCenter.addObserver(this, callfuncO_selector(CCImageNotificationCenter::imageLoaded), observerIDstr->getCString(), new imgstruct(imageName, observerIDstr->getCString(), layer, useMask)); m_observerID++;
return observerIDstr->getCString();
} void CCImageNotificationCenter::removeObserver(const char *name)
{
m_notificationCenter.removeObserver(this, name);
} void CCImageNotificationCenter::postNotification(const char *name, CCObject *object)
{
m_notificationCenter.postNotification(name, object);
} void CCImageNotificationCenter::imageLoaded(CCObject *obj)
{
imgstruct* img = (imgstruct*)obj;
CCLOG("imageLoaded success,imageName:%s",img->imageName.c_str());
CCSprite* sprite = CCImageNotificationCenter::getSpriteFromWriteablePath(img->imageName.c_str());
CCLOG("got sprite 0x%X", sprite);
if (img->useMask)
{
img->layer->addChild(CCImageNotificationCenter::createMaskedSprite(sprite,"mask.png"));
}
else
{
float scale_ = (float) img->layer->getContentSize().width / (float)sprite->getContentSize().width;
sprite->setAnchorPoint(ccp(,));
sprite->setScale( scale_ );
img->layer->addChild(sprite);
}
this->removeObserver(img->observerId.c_str());
img->release();
} CCSprite* CCImageNotificationCenter::getSpriteFromWriteablePath(const char* name)
{
std::string path = CCFileUtils::sharedFileUtils()->getWriteablePath();
path += name;
FILE* fp = fopen(path.c_str(),"rb");
if (!fp)
{
return NULL;
}
fseek(fp,,SEEK_END);
int len = ftell(fp);
fseek(fp,,SEEK_SET);
char* buf = (char*)malloc(len);
fread(buf,len,,fp);
fclose(fp);
CCImage* img = new CCImage;
img->initWithImageData(buf,len);
free(buf);
cocos2d::CCTexture2D* texture = new cocos2d::CCTexture2D();
bool isImg = texture->initWithImage(img);
img->release();
if (!isImg)
{
delete texture;
return CCSprite::create("default.png");//加载资源并非图片时返回的默认图
}
CCSprite* sprite = CCSprite::createWithTexture(texture);
texture->release();
return sprite;
}
实现ImageDownload类
class ImageDownloader : public cocos2d::CCObject
{
DECLARE_SINGLETON_CLASS(ImageDownloader);
public:
ImageDownloader();
~ImageDownloader(); void CreateLuaFunc(); void SendHttpRequest(const char* url, CCLayer* layer, const char* filename);
void HttpRequestComplete(CCHttpClient *sender, CCHttpResponse *response); CCString observerID;
CCLayer* container;
bool useMask;
};
void ImageDownloader::SendHttpRequest(const char* url, CCLayer* layer, const char* filename)
{
CCHttpRequest* request = new CCHttpRequest();
this->container = layer;
if (this->container)
{
CCImageNotificationCenter::CreateInstance();
this->observerID = CCImageNotificationCenter::GetInstance()->addObserver(filename,container,useMask);
}
request->setUrl(url);
// request->setUrl("http://neoimaging.beareyes.com.cn/png2/ni_png_2_1518.png");
request->setRequestType(CCHttpRequest::kHttpGet);
request->setResponseCallback(this, httpresponse_selector(ImageDownloader::HttpRequestComplete));
request->setTag("GET IMAGE");
CCHttpClient::getInstance()->send(request);
request->release();
} void ImageDownloader::HttpRequestComplete(CCHttpClient *sender, CCHttpResponse *response)
{
if (!response)
{
return;
} // You can get original request type from: response->request->reqType
if ( != strlen(response->getHttpRequest()->getTag()))
{
CCLog("%s completed", response->getHttpRequest()->getTag());
} int statusCode = response->getResponseCode();
char statusString[] = {};
sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
CCLog("response code: %d", statusCode); if (!response->isSucceed())
{
CCLog("response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
return;
} // dump data
std::vector<char> *buffer = response->getResponseData();
std::string path = CCFileUtils::sharedFileUtils()->getWriteablePath();
std::string bufffff(buffer->begin(),buffer->end()); //保存到本地文件
path += "dl.png";
CCLOG("path: %s",path.c_str());
FILE *fp = fopen(path.c_str(), "wb+");
fwrite(bufffff.c_str(), ,buffer->size(), fp);
fclose(fp); //传入container的下载请求会添加侦听,待下载完毕自动添加到container上
if (this->container)
{
// container 是一个CCLayer ,用来显示动态加载的资源
CCImageNotificationCenter::GetInstance()->cocos2d::CCNotificationCenter::postNotification(this->observerID.getCString());
}
}
Cocos2d-x利用CCHttpRequest获取网络图片并显示的更多相关文章
- cocos2d-x CCHttpRequest获取网络图片并显示
转自:http://www.cnblogs.com/hzj730/p/3178431.html //图片结构 class imgstruct : public CCObject { public: i ...
- 获取网络图片并显示在picturbox上,byte[]数组转换成Image:
private void getWebPicture_Click(object sender, EventArgs e) { WebRequest request = WebRequest.Creat ...
- 【cocos2d-x 手游研发小技巧(5)获取网络图片缓存并展示】
今天是年前最后一天上班了,最后一天上班,祝大家马上有各种东西,最后一天也给写一点干货,就是获取网络图片: 经过自己简单封装了一下,实现了获取网络图片,按照比例展示出来,实现方法是cocos2dx - ...
- cocos2d-x C++ 获取网络图片缓存并展示
#ifndef __HttpGetImg__ #define __HttpGetImg__ #include "cocos2d.h" #include "HttpRequ ...
- tableView 获取网络图片,并且设置为圆角(优化,fps)
代码地址如下:http://www.demodashi.com/demo/11088.html 一.准备工作 例子比较精简,没有什么特殊要求,具备Xocde8.0左右版本的就好 二.程序实现 1.相关 ...
- 利用LruCache载入网络图片实现图片瀑布流效果(改进版)
PS: 2015年1月20日21:37:27 关于LoadImageAsyncTask和checkAllImageViewVisibility可能有点小bug 改动后的代码请參见升级版本号的代码 ht ...
- (转)利用libcurl获取新浪股票接口, ubuntu和openwrt实验成功(三)
1. 利用 CURLOPT_WRITEFUNCTION 设置回调函数, 利用 CURLOPT_WRITEDATA 获取数据指针 官网文档如下 CALLBACK OPTIONS CURLOPT_WRI ...
- 基于MVC4+EasyUI的Web开发框架经验总结(1)-利用jQuery Tags Input 插件显示选择记录
最近花了不少时间在重构和进一步提炼我的Web开发框架上,力求在用户体验和界面设计方面,和Winform开发框架保持一致,而在Web上,我主要采用EasyUI的前端界面处理技术,走MVC的技术路线,在重 ...
- 十九、利用OGNL获取ValueStack中:根栈和contextMap中的数据
利用OGNL获取ValueStack中:根栈和contextMap中的数据 原则:OGNL表达式如果以#开头,访问的contextMap中的数据 如果不以#开头,是访问的根栈中的对象的属性(List集 ...
随机推荐
- RequireJS入门(三)转
这篇来写一个具有依赖的事件模块event.event提供三个方法bind.unbind.trigger来管理DOM元素事件. event依赖于cache模块,cache模块类似于jQuery的$.da ...
- CleanMyMac2清理 lanchpad里面的图标没了
好吧.用CleanMyMac2 清理了系统(10.9)之后图标没了.解决办法是: Launchpad存储在一个SQLite数据库中,存储目录是: ~/Library/Application Suppo ...
- Linux makefile教程之概述一[转]
概述—— 什么是makefile?或许很多Winodws的程序员都不知道这个东西,因为那些 Windows的IDE都为你做了这个工作,但我觉得要作一个好的和professional的程序员,makef ...
- window 与ubuntu共享文件 hgfs下为空和不用每次挂载hgfs的方法
解决hgfs为空的方法: sudo apt-get install open-vm-dkms sudo mount -t vmhgfs .host:/ /mnt/hgfs 解决每次都要挂载的方法: 1 ...
- ADO.NET+Access: 1,标准表达式中数据类型不匹配
ylbtech-Error-ADO.NET+Access: 1,标准表达式中数据类型不匹配. 1.A,错误代码返回顶部 1,标准表达式中数据类型不匹配. 1.B,出错原因分析返回顶部 未解决 1. ...
- JavaScript/jQuery 表单美化插件小结
Niceforms Niceforms是一款独立的表单美化工具,当前版本为2.0 官方主页:http://www.emblematiq.com/lab/niceforms/ 官方演示:http://w ...
- D.xml
pre{ line-height:1; color:#1e1e1e; background-color:#f0f0f0; font-size:16px;}.sysFunc{color:#627cf6; ...
- 阿里巴巴2013年实习生笔试题B
阿里巴巴集团2013实习生招聘技术类笔试题(B) 一.单向选择题 1.在常用的网络协议中,___B__是面向连接的.有重传功能的协议. A. IP B. TCP C. UDP D. DXP 2.500 ...
- Start SparkR in RStudio
Sys.setenv(SPARK_HOME="/usr/spark") .libPaths(c(file.path(Sys.getenv("SPARK_HOME" ...
- 获取子窗口中使用jQuery.data()设置的参数
http://hyj1254.iteye.com/blog/643035 假设在iframe子窗口中设置了$('#mydata').data('key','hello world'); 那在包含ifr ...