cocos2d-x CCHttpRequest获取网络图片并显示
转自:http://www.cnblogs.com/hzj730/p/3178431.html
//图片结构
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获取网络图片并显示
利用CCHttpRequest获取网上http地址的图片并缓存到本地生成CCSprite用于显示 //图片结构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 ...
- 分享一个安卓中异步获取网络图片并自适应大小的第三方程序(来自github)
安卓中获取网络图片,生成缓存 用安卓手机,因为手机流量的限制,所以我们在做应用时,要尽量为用户考虑,尽量少耗点用户的流量,而在应用中网络图片的显示无疑是消耗流量最大的,所以我们可以采取压缩图片或者将图 ...
- 根据url路径获取图片并显示到ListView中
项目开发中我们需要从网络获取图片显示到控件中,很多开源框架如Picasso可以实现图片下载和缓存功能.这里介绍的是一种简易的网络图片获取方式并把它显示到ListView中. 本案例实现的效果如下: 项 ...
- tableView 获取网络图片,并且设置为圆角(优化,fps)
代码地址如下:http://www.demodashi.com/demo/11088.html 一.准备工作 例子比较精简,没有什么特殊要求,具备Xocde8.0左右版本的就好 二.程序实现 1.相关 ...
- URL转Drawable之 Android中获取网络图片的三种方法
转载自: http://doinone.iteye.com/blog/1074283 Android中获取网络图片是一件耗时的操作,如果直接获取有可能会出现应用程序无响应(ANR:Applicatio ...
- js获取当前时间显示在页面上
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
随机推荐
- 新手学习JSP+Servlet笔记一
作为一个新手,初次接触jsp,servlet,习惯了后台的开发,前台的知识一窍不通,利用闲暇时间,给自己补补,从MyEclipse开始. 安装好MyEclipse之后,没有安装程序的可以下载 http ...
- Perl语言学习笔记 15 智能匹配与give-when结构
1.智能匹配操作符 替代绑定操作符: 在哈希中查找某一个键: 比較两个数组是否全然同样: 查找列表中是否存在某个元素: 智能匹配操作符与顺序无关.~~ 左右元素能够互换 2.智能操作符优先级 3.gi ...
- Java8中 Date和LocalDateTime的相互转换
一.在Java 8中将Date转换为LocalDateTime 方法1: 将Date转换为LocalDatetime,我们可以使用以下方法: 1.从日期获取ZonedDateTime并使用其方法toL ...
- 开源监控系统Prometheus介绍
前言 Prometheus是CNCF的一个开源项目,Google BorgMon监控系统的开源版本,是一个系统和服务的监控系统.周期性采集metrics指标,匹配规则和展示结果,以及触发某些条件的告警 ...
- TCP交换数据流——Nagle算法简单记录
Nagle算法: 该算法提出的目的是想解决网络中大量的小的TCP数据包造成网络拥塞的问题,举个例子,当客户端要发送一个字节的TCP数据包到服务器时,我们实际上产生了41字节长的分组:包括20字节的IP ...
- MVC教程--MiniProfiler.EF监控调试MVC和EF的性能
上一篇谈到mvc中ef输出执行sql日志:来谈用mvc开发项目的调试和性能监控.EF框架自动给我生成sql语句,当我们的程序遇到性能问题的时候我们可以用MiniProfiler.EF来监控调试MVC和 ...
- 九度OJ 1165:字符串匹配 (模式匹配)
时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:3219 解决:1149 题目描述: 读入数据string[ ],然后读入一个短字符串.要求查找string[ ]中和短字符串的所有匹配,输出 ...
- 九度OJ 1082:代理服务器 (DP)
时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:1871 解决:574 题目描述: 使用代理服务器能够在一定程度上隐藏客户端信息,从而保护用户在互联网上的隐私.我们知道n个代理服务器的IP地 ...
- iOS与H5交互及UIWebView缓存
iOS原生App与H5页面交互笔记 最近在做一个项目用到了原生App与H5交互,之前有做过简单的H5页面直接调用原生方法的例子,就是利用UIWebView中的代理方法 //webview每次加载之前都 ...
- ExtJS教程(5)---Ext.data.Model之高级应用
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/jaune161/article/details/37391399 1.Model的数据验证 这里借助 ...