`
445822357
  • 浏览: 741089 次
文章分类
社区版块
存档分类
最新评论

cocos2d-x 聊天输入框实现

 
阅读更多

转自:http://blog.csdn.net/we000636/article/details/8829172


聊天输入框 (单行输入框 ,多行可自己扩展)

实现功能:

1.普通输入

2.设置输入框显示最大宽度(PT值,cocos2d-x坐标值)

3.设置输入框允许的最大字符数量(字符Unicode)

4.输入框自动缩进(当输入字符串数量超过显示框最大宽度时,会自动向左缩进,显示最新字符串


输入框实现代码

头文件:

  1. #ifndefCursorInputDemo_CursorTextField_h
  2. #defineCursorInputDemo_CursorTextField_h
  3. #include"cocos2d.h"
  4. USING_NS_CC;
  5. classCursorTextField:publicCCTextFieldTTF,publicCCTextFieldDelegate,publicCCTouchDelegate
  6. {
  7. private:
  8. //点击开始位置
  9. CCPointm_beginPos;
  10. //光标精灵
  11. CCSprite*m_pCursorSprite;
  12. //光标动画
  13. CCAction*m_pCursorAction;
  14. //光标坐标
  15. CCPointm_cursorPos;
  16. //输入框长度
  17. floatinputFrameWidth;
  18. //允许输入的最大字符数Unicode
  19. floatinputMaxLength;
  20. intnLenCount;
  21. int*codeNumType;//每个字符对应的字节数量
  22. intcodeCur;//当前第几个字符
  23. intstartCur;//行开头字符下标
  24. intendCur;//行末尾下标
  25. //输入框总内容
  26. std::string*m_pInputText;
  27. std::stringinpuText;//当前输入框内容
  28. public:
  29. CursorTextField();
  30. ~CursorTextField();
  31. //static
  32. staticCursorTextField*textFieldWithPlaceHolder(constchar*placeholder,constchar*fontName,floatfontSize);
  33. //CCLayer
  34. voidonEnter();
  35. voidonExit();
  36. boolinit();
  37. //初始化光标精灵
  38. voidinitCursorSprite(intnHeight);
  39. //CCTextFieldDelegate
  40. virtualboolonTextFieldAttachWithIME(CCTextFieldTTF*pSender);
  41. virtualboolonTextFieldDetachWithIME(CCTextFieldTTF*pSender);
  42. virtualboolonTextFieldInsertText(CCTextFieldTTF*pSender,constchar*text,intnLen);
  43. virtualboolonTextFieldDeleteBackward(CCTextFieldTTF*pSender,constchar*delText,intnLen);
  44. //CCLayerTouch
  45. boolccTouchBegan(CCTouch*pTouch,CCEvent*pEvent);
  46. voidccTouchEnded(CCTouch*pTouch,CCEvent*pEvent);
  47. //判断是否点击在TextField处
  48. boolisInTextField(CCTouch*pTouch);
  49. //得到TextField矩形
  50. CCRectgetRect();
  51. //打开输入法
  52. voidopenIME();
  53. //关闭输入法
  54. voidcloseIME();
  55. constchar*getInputText();
  56. voidsetInpuntText(char*text);
  57. voidsetInputWidth(floatwidth);
  58. voidsetInputMaxLength(floatlength);
  59. intUtf82Unicode(LPWSTRout,intoutsize,LPSTRin,intinsize);
  60. };
  61. #endif


cpp文件:

  1. #include"CursorTextField.h"
  2. conststaticfloatDELTA=0.5f;
  3. usingnamespacecocos2d;
  4. usingnamespacestd;
  5. CursorTextField::CursorTextField()
  6. {
  7. CCTextFieldTTF();
  8. m_pCursorSprite=NULL;
  9. m_pCursorAction=NULL;
  10. m_pInputText=NULL;
  11. codeNumType=NULL;
  12. }
  13. CursorTextField::~CursorTextField()
  14. {
  15. CC_SAFE_DELETE(m_pInputText);
  16. CC_SAFE_DELETE_ARRAY(codeNumType);
  17. }
  18. voidCursorTextField::onEnter()
  19. {
  20. CCTextFieldTTF::onEnter();
  21. CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,false);
  22. this->setDelegate(this);
  23. }
  24. CursorTextField*CursorTextField::textFieldWithPlaceHolder(constchar*placeholder,constchar*fontName,floatfontSize)
  25. {
  26. CursorTextField*pRet=newCursorTextField();
  27. if(pRet&&pRet->initWithString("",fontName,fontSize))
  28. {
  29. pRet->autorelease();
  30. if(placeholder)
  31. {
  32. pRet->setPlaceHolder(placeholder);
  33. }
  34. pRet->init();
  35. pRet->initCursorSprite(fontSize);
  36. pRet->setHorizontalAlignment(kCCTextAlignmentLeft);
  37. returnpRet;
  38. }
  39. CC_SAFE_DELETE(pRet);
  40. returnNULL;
  41. }
  42. boolCursorTextField::init(){
  43. this->inputFrameWidth=400;
  44. this->inputMaxLength=38;
  45. this->nLenCount=0;
  46. this->codeNumType=newint[50];
  47. this->codeCur=0;
  48. this->startCur=0;
  49. this->endCur=0;
  50. inpuText="";
  51. returntrue;
  52. }
  53. voidCursorTextField::initCursorSprite(constintmHeight)
  54. {
  55. //初始化光标
  56. constintcolumn=4;
  57. constintnHeight=(constint)mHeight;
  58. intpixels[25][column];
  59. for(inti=0;i<nHeight;++i){
  60. for(intj=0;j<column;++j){
  61. pixels[i][j]=0xffffffff;
  62. }
  63. }
  64. CCTexture2D*texture=newCCTexture2D();
  65. texture->initWithData(pixels,kCCTexture2DPixelFormat_RGB888,1,1,CCSizeMake(column,nHeight));
  66. m_pCursorSprite=CCSprite::createWithTexture(texture);
  67. CCSizewinSize=getContentSize();
  68. m_cursorPos=ccp(0,winSize.height/2);
  69. m_pCursorSprite->setPosition(m_cursorPos);
  70. this->addChild(m_pCursorSprite);
  71. m_pCursorSprite->setVisible(false);
  72. m_pCursorAction=CCRepeatForever::create((CCActionInterval*)CCSequence::create(CCFadeOut::create(0.25f),CCFadeIn::create(0.25f),NULL));
  73. m_pCursorSprite->runAction(m_pCursorAction);
  74. m_pInputText=newstd::string();
  75. }
  76. boolCursorTextField::ccTouchBegan(cocos2d::CCTouch*pTouch,cocos2d::CCEvent*pEvent)
  77. {
  78. m_beginPos=pTouch->getLocation();
  79. returntrue;
  80. }
  81. CCRectCursorTextField::getRect()
  82. {
  83. CCSizesize=getContentSize();
  84. returnCCRectMake(0,-size.height/2,inputFrameWidth,size.height);
  85. }
  86. //获取输入框内容
  87. constchar*CursorTextField::getInputText(){
  88. constchar*text=m_pInputText->c_str();
  89. returntext;
  90. }
  91. //设置输入框内容
  92. voidCursorTextField::setInpuntText(char*text){
  93. *m_pInputText="";
  94. setString(text);
  95. m_pCursorSprite->setPositionX(0);
  96. CC_SAFE_DELETE_ARRAY(codeNumType);
  97. codeNumType=newint[50];
  98. codeCur=0;
  99. startCur=0;
  100. endCur=0;
  101. inpuText="";
  102. }
  103. //设置输入框宽度一旦字符串宽度超度这个长度字符串会自动向左缩进
  104. voidCursorTextField::setInputWidth(floatwidth){
  105. this->inputFrameWidth=width;
  106. }
  107. //设置输入宽显示的最大字符数量Unicode
  108. voidCursorTextField::setInputMaxLength(floatlength){
  109. this->inputMaxLength=length;
  110. }
  111. //判断点击事件,是否响应在输入框范围内
  112. boolCursorTextField::isInTextField(cocos2d::CCTouch*pTouch)
  113. {
  114. returngetRect().containsPoint(convertTouchToNodeSpaceAR(pTouch));
  115. }
  116. voidCursorTextField::ccTouchEnded(cocos2d::CCTouch*pTouch,cocos2d::CCEvent*pEvent)
  117. {
  118. CCPointendPos=pTouch->getLocation();
  119. //判断是否为点击事件
  120. if(::abs(endPos.x-m_beginPos.x)>DELTA||
  121. ::abs(endPos.y-m_beginPos.y))
  122. {
  123. //不是点击事件
  124. m_beginPos.x=m_beginPos.y=-1;
  125. return;
  126. }
  127. //判断是打开输入法还是关闭输入法
  128. isInTextField(pTouch)?openIME():closeIME();
  129. }
  130. //弹出手机键盘时响应事件
  131. boolCursorTextField::onTextFieldAttachWithIME(cocos2d::CCTextFieldTTF*pSender)
  132. {
  133. if(m_pInputText->empty()){
  134. returnfalse;
  135. }
  136. m_pCursorSprite->setPositionX(getContentSize().width);
  137. returnfalse;
  138. }
  139. //当有输入进来时响应
  140. //@parampSender发送事件对象
  141. //@paramtext输入内容
  142. //@param内容字节长度
  143. boolCursorTextField::onTextFieldInsertText(cocos2d::CCTextFieldTTF*pSender,constchar*text,intnLen)
  144. {
  145. std::stringsText=m_pInputText->c_str();
  146. wchar_t*wText=newwchar_t[200];
  147. chart[200];
  148. memset(t,0,200);
  149. strcpy(t,sText.c_str());
  150. //将字符串转换为Unicode,并返回Unicode字符数量
  151. intcou=Utf82Unicode(wText,200,t,sText.length());
  152. //当字符数量超过规定值不做处理
  153. if(cou>=inputMaxLength)returntrue;
  154. //屏蔽回车输入
  155. if(text[0]=='\n')
  156. returntrue;
  157. //输入框总内容添加
  158. m_pInputText->append(text);
  159. //测试
  160. CCLabelTTF*ttf=CCLabelTTF::create(text,"Verdana-Bold",26);
  161. floatteWidth=ttf->getContentSize().width;
  162. CCLOG("anycodelength---%f",teWidth);
  163. //输入框当前字符串添加
  164. inpuText.append(text);
  165. //当前字符的长度
  166. codeNumType[codeCur++]=nLen;
  167. std::string*localText=m_pInputText;
  168. setString(m_pInputText->c_str());
  169. //如果总字符串的长度大于指定宽度
  170. if(getContentSize().width>inputFrameWidth){
  171. //大于,截取字符串,直到字符串的长度小于指定宽度为止
  172. setString(inpuText.c_str());
  173. while(getContentSize().width>inputFrameWidth){
  174. intnnLen=nLen;
  175. if(codeNumType[startCur]==1){
  176. nnLen=1;
  177. }
  178. if(codeNumType[startCur]==3){
  179. nnLen=3;
  180. }
  181. startCur++;
  182. nLenCount+=nnLen;
  183. floatgap=localText->size()-nLenCount;
  184. inpuText=localText->substr(nLenCount,gap);
  185. setString(inpuText.c_str());
  186. floatcoWidth=getContentSize().width;
  187. }
  188. }
  189. else{
  190. //小于,直接设置显示总字符串
  191. nLenCount=0;
  192. startCur=0;
  193. setString(m_pInputText->c_str());
  194. }
  195. //设置光标位置
  196. m_pCursorSprite->setPositionX(getContentSize().width);
  197. CC_SAFE_DELETE_ARRAY(wText);
  198. returntrue;
  199. }
  200. //当有输入进来时响应
  201. //@parampSender发送事件对象
  202. //@paramtext删除内容
  203. //@param内容字节长度
  204. boolCursorTextField::onTextFieldDeleteBackward(cocos2d::CCTextFieldTTF*pSender,constchar*delText,intnLen)
  205. {
  206. //将总字符串长度减去nLen字节长
  207. m_pInputText->resize(m_pInputText->size()-nLen);
  208. //当前字符数减一
  209. codeNumType[codeCur--]=0;
  210. std::string*localText=m_pInputText;
  211. setString(m_pInputText->c_str());
  212. if(getContentSize().width>inputFrameWidth){
  213. //大于指定宽度,截取字符串,直到字符串长度小于指定宽度
  214. while(getContentSize().width>inputFrameWidth){
  215. intnnLen=nLen;
  216. if(codeNumType[startCur-1]==1){
  217. nnLen=1;
  218. }
  219. if(codeNumType[startCur-1]==3){
  220. nnLen=3;
  221. }
  222. nLenCount-=nnLen;
  223. startCur--;
  224. if(startCur<=0)
  225. startCur=0;
  226. if(nLenCount<=0)
  227. nLenCount=0;
  228. floatgap=localText->size()-nLenCount;
  229. conststd::stringtext=localText->substr(nLenCount,gap);
  230. setString(text.c_str());
  231. inpuText=text;
  232. }
  233. }
  234. else{
  235. nLenCount=0;
  236. startCur=0;
  237. setString(m_pInputText->c_str());
  238. }
  239. //设置光标位置
  240. m_pCursorSprite->setPositionX(getContentSize().width);
  241. if(m_pInputText->empty()){
  242. m_pCursorSprite->setPositionX(0);
  243. }
  244. returntrue;
  245. }
  246. boolCursorTextField::onTextFieldDetachWithIME(cocos2d::CCTextFieldTTF*pSender)
  247. {
  248. returnfalse;
  249. }
  250. voidCursorTextField::openIME()
  251. {
  252. m_pCursorSprite->setVisible(true);
  253. this->attachWithIME();
  254. }
  255. voidCursorTextField::closeIME()
  256. {
  257. m_pCursorSprite->setVisible(false);
  258. this->detachWithIME();
  259. }
  260. voidCursorTextField::onExit()
  261. {
  262. CCTextFieldTTF::onExit();
  263. CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
  264. }
  265. intCursorTextField::Utf82Unicode(LPWSTRout,intoutsize,LPSTRin,intinsize)
  266. {
  267. //-------------------------------------------------------------------------------------------
  268. //参数有效性判断
  269. if(out==NULL||in==NULL||insize<0)
  270. {
  271. return-1;
  272. }
  273. inttypeCount=0;
  274. inttotalNum=0;
  275. char*p=in;
  276. for(inti=0;i<insize;i++)
  277. {
  278. if(*p>=0x00&&*p<=0x7f)//说明最高位为'0',这意味着utf8编码只有1个字节!
  279. {
  280. p++;
  281. totalNum+=1;
  282. }
  283. elseif((*p&(0xe0))==0xc0)//只保留最高三位,看最高三位是不是110,如果是则意味着utf8编码有2个字节!
  284. {
  285. p++;
  286. p++;
  287. totalNum+=1;
  288. }
  289. elseif((*p&(0xf0))==0xe0)//只保留最高四位,看最高三位是不是1110,如果是则意味着utf8编码有3个字节!
  290. {
  291. p++;
  292. p++;
  293. p++;
  294. totalNum+=1;
  295. }
  296. }
  297. if(outsize<totalNum)//参数有效性判断!
  298. {
  299. return-1;
  300. }
  301. //------------------------------------------------
  302. intresultsize=0;
  303. p=in;
  304. char*tmp=(char*)out;
  305. while(*p)
  306. {
  307. if(*p>=0x00&&*p<=0x7f)//说明最高位为'0',这意味着utf8编码只有1个字节!
  308. {
  309. *tmp=*p;
  310. tmp++;
  311. //*tmp='/0';
  312. tmp++;
  313. resultsize+=1;
  314. }
  315. elseif((*p&0xe0)==0xc0)//只保留最高三位,看最高三位是不是110,如果是则意味着utf8编码有2个字节!
  316. {
  317. wchar_tt=0;
  318. chart1=0;
  319. chart2=0;
  320. t1=*p&(0x1f);//高位的后5位!(去除了头部的110这个标志位)
  321. p++;
  322. t2=*p&(0x3f);//低位的后6位!(去除了头部的10这个标志位)
  323. *tmp=t2|((t1&(0x03))<<6);
  324. tmp++;
  325. *tmp=t1>>2;//留下其保留的三位
  326. tmp++;
  327. resultsize+=1;
  328. }
  329. elseif((*p&(0xf0))==0xe0)//只保留最高四位,看最高三位是不是1110,如果是则意味着utf8编码有3个字节!
  330. {
  331. wchar_tt=0;
  332. wchar_tt1=0;
  333. wchar_tt2=0;
  334. wchar_tt3=0;
  335. t1=*p&(0x1f);
  336. p++;
  337. t2=*p&(0x3f);
  338. p++;
  339. t3=*p&(0x3f);
  340. *tmp=((t2&(0x03))<<6)|t3;
  341. tmp++;
  342. *tmp=(t1<<4)|(t2>>2);
  343. tmp++;
  344. resultsize+=1;
  345. }
  346. p++;
  347. }
  348. /*不考虑结束符,如果考虑则打开此段!
  349. *tmp='/0';
  350. tmp++;
  351. *tmp='/0';
  352. resultsize+=2;
  353. */
  354. returnresultsize;
  355. }

上面代码是通是UTF-8转Unicode来获取字符数量。当输入字符数量过多时,可能字节大小会超过声明的char数组大小,导致出现越界情况,程序崩溃。

解决方法一:根据限定字符数量,将char数组大小声明为最大数量,来避免越界情况出生

解决方法二:定义一个私有变量unicodeCount(名字随意取)来记录输入字符的总数量。由于onTextFieldInsertText,onTextFieldDeleteBackward这两个方法都是在我们输入一个完整字符或者减去一个完整字符时调用一次,所以将unicodeCount++放入onTextFieldInsertText,将unicodeCount--放入onTextFieldDeleteBackward中,可以完成输入字符数量的保存。这样就可以免去UTF-8转Unicode的操作,完全避免越界情况产生,也提高了效率


效率方面尚未优化,请参考自行优化,只提供一个解决思路

接下来将会写一篇光于cocos2d-普通文本显示框,不支持富文本,主要提供自动换行解决思路,以解决当前CCLabelTTF自动换行Bug的替代方案


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics