cocos2d-x 聊天输入框实现

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


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

实现功能:

1.普通输入

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

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

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


输入框实现代码

头文件:

[cpp]  view plain copy
  1. #ifndef CursorInputDemo_CursorTextField_h  
  2. #define CursorInputDemo_CursorTextField_h  
  3.   
  4. #include "cocos2d.h"  
  5.   
  6. USING_NS_CC;  
  7.   
  8. class CursorTextField: public CCTextFieldTTF, public CCTextFieldDelegate, public CCTouchDelegate  
  9. {  
  10. private:  
  11.     // 点击开始位置  
  12.     CCPoint m_beginPos;  
  13.     // 光标精灵  
  14.     CCSprite *m_pCursorSprite;  
  15.     // 光标动画  
  16.     CCAction *m_pCursorAction;  
  17.     // 光标坐标  
  18.     CCPoint m_cursorPos;  
  19.     //输入框长度  
  20.     float inputFrameWidth;  
  21.     //允许输入的最大字符数Unicode  
  22.     float inputMaxLength;  
  23.     int nLenCount;  
  24.     int* codeNumType;    //每个字符对应的字节数量  
  25.     int codeCur;         //当前第几个字符  
  26.     int startCur;        //行开头字符下标  
  27.     int endCur;          //行末尾下标  
  28.     // 输入框总内容  
  29.     std::string *m_pInputText;  
  30.     std::string inpuText; //当前输入框内容  
  31. public:  
  32.     CursorTextField();  
  33.     ~CursorTextField();  
  34.     // static  
  35.     static CursorTextField* textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize);  
  36.     // CCLayer  
  37.     void onEnter();  
  38.     void onExit();  
  39.     bool init();  
  40.     // 初始化光标精灵  
  41.     void initCursorSprite(int nHeight);  
  42.   
  43.     // CCTextFieldDelegate  
  44.     virtual bool onTextFieldAttachWithIME(CCTextFieldTTF *pSender);  
  45.     virtual bool onTextFieldDetachWithIME(CCTextFieldTTF * pSender);  
  46.     virtual bool onTextFieldInsertText(CCTextFieldTTF * pSender, const char * text, int nLen);  
  47.     virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * pSender, const char * delText, int nLen);  
  48.   
  49.     // CCLayer Touch  
  50.     bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);  
  51.     void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);  
  52.   
  53.     // 判断是否点击在TextField处  
  54.     bool isInTextField(CCTouch *pTouch);  
  55.     // 得到TextField矩形  
  56.     CCRect getRect();  
  57.   
  58.     // 打开输入法  
  59.     void openIME();  
  60.     // 关闭输入法  
  61.     void closeIME();  
  62.   
  63.     const char* getInputText();  
  64.     void setInpuntText(char* text);  
  65.     void setInputWidth(float width);  
  66.     void setInputMaxLength(float length);  
  67.   
  68.     int Utf82Unicode(LPWSTR out,  int outsize , LPSTR in,int insize);  
  69. };  
  70.   
  71. #endif  


cpp文件:

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

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

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

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


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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值