用cocos2dx实现聊天效果

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


用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;
}


出来的效果如下:


大家也可自己动手试试

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值