用cocos2dx实现聊天效果

来源:互联网 发布:整点报时软件 编辑:程序博客网 时间:2024/06/13 00:07

首先来看一下现在流行的短信形式,以下的图是随便找的~~


用cocos2dx来实现它其实非常简单,

需要一个9妹,一个CCLabelTTF就可以实现,OK,先讲一下思路,再上代码

1 把要显示的字符放进LabelITTF

2 获取字符串控件的宽和高与9妹对比,如果小于9妹,则用9妹原来的宽高,否则计算应该把9妹拉到适合的大小

3 设置9妹的大小,就完成了。

代码也非常简单,上面上代码片段。

注意:资源我用的是28*28图片

test.h

class test:public cocos2d::CCNode{public:test(const char* backgroundImage,const char* pContext, int fontsize);~test(void);virtual bool init(); static test* create(const char* backgroundImage,const char* pContext, int fontsize = 20);private:cocos2d::extension::CCScale9Sprite* _background;// 背景图 -9妹cocos2d::CCLabelTTF* _context;// 显示的字符std::string _szFile;// 背景资源std::string _szContext;// 字符int _fontSize;// 字符大小};



test.cpp

test::test(const char* backgroundImage,const char* pContext, int fontsize) : _szFile(backgroundImage),_szContext(pContext), _fontSize(fontsize){}test* test::create(const char* backgroundImage, const char* pContext, int fontsize /* = 20 */){test* pRet = new test(backgroundImage, pContext, fontsize);if (pRet && pRet->init()){pRet->autorelease();return pRet;}else{delete pRet;pRet = NULL; return NULL;}}bool test::init(){if (!CCNode::init())return false;CCSprite* tmp = CCSprite::create(_szFile.c_str());CCSize size = tmp->getContentSize();tmp->release();_background = CCScale9Sprite::create(_szFile.c_str());_background->setPosition(ccp(0, 0));_background->setAnchorPoint(CCPointZero);addChild(_background);_context = CCLabelTTF::create(_szContext.c_str(), "", _fontSize);addChild(_context);float h =  _context->getContentSize().height;float w = _context->getContentSize().width;_background->setContentSize(CCSizeMake(w, h));// 把显示的字符调整到控件的中间CCSize size = _background->getContentSize();_context->setPosition(ccp(size.width / 2, size.height / 2));return true;}


出来的效果如下:


大家也可自己动手试试

原创粉丝点击