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 ...
- Gunicorn、Supervisor
简介 Gunicorn来源于Ruby的unicorn项目,是一个Python WSGI HTTP Server,通过pre-fork worker模型来管理和维护worker. 简而言之就是通过多进程 ...
- JavaScript之this的工作原理
JavaScript 有一套完全不同于其它语言的对 this 的处理机制. 在五种不同的情况下 ,this 指向的各不相同. 1.全局范围内 当在全部范围内使用 this,它将会指向全局对象. 2.函 ...
- 【TensorFlow-windows】(六) CNN之Alex-net的测试
主要内容: 1.CNN之Alex-net的测试 2.该实现中的函数总结 平台: 1.windows 10 64位 2.Anaconda3-4.2.0-Windows-x86_64.exe (当时TF还 ...
- kafka source type
https://flume.apache.org/FlumeUserGuide.html # example.conf: A single-node Flume configuration # Nam ...
- 【题解】P4799[CEOI2015 Day2]世界冰球锦标赛
[题解][P4799 CEOI2015 Day2]世界冰球锦标赛 发现买票顺序和答案无关,又发现\(n\le40\),又发现从后面往前面买可以通过\(M\)来和从前面往后面买的方案进行联系.可以知道是 ...
- API的理解和使用——列表类型的命令
列表类型的命令及对应的时间复杂度 操作 命令 功能 时间复杂度 添加 rpush key value [value ...] 向右插入 O(k),k是元素个数 lpush key value [val ...
- CentOS7的yum安装mysql
CentOS7的yum源中默认好像是没有mysql的.为了解决这个问题,我们要先下载mysql的repo源. 1. 下载mysql的repo源 $ wget http://repo.mysql.com ...
- PermissionError: [Errno 13] Permission denied:
在ubuntu系统下使用pip 命令安装包时,出现以下类似错误提示: PermissionError: [Errno 13] Permission denied: '/usr/local/lib/py ...
- 测试drawable animation
public class DAActivity extends Activity implements OnClickListener { private ImageView iv_da_mm; pr ...