cocos2d-x 聊天输入框实现

本文介绍了一个自定义的文本输入框组件,实现了普通输入、最大宽度设置、最大字符数量限制、自动缩进等功能。通过Cocos2d-x引擎的CCTextFieldTTF类进行扩展,提供了丰富的输入体验,适用于需要精细控制输入行为的游戏或应用开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://blog.youkuaiyun.com/we000636/article/details/8829172

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

实现功能:

1.普通输入

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

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

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


输入框实现代码

头文件:

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

#include "cocos2d.h"

USING_NS_CC;

class CursorTextField: public CCTextFieldTTF, public CCTextFieldDelegate, public CCTouchDelegate
{
private:
	// 点击开始位置
	CCPoint m_beginPos;
	// 光标精灵
	CCSprite *m_pCursorSprite;
	// 光标动画
	CCAction *m_pCursorAction;
	// 光标坐标
	CCPoint m_cursorPos;
	//输入框长度
	float inputFrameWidth;
	//允许输入的最大字符数Unicode
	float inputMaxLength;
	int nLenCount;
	int* codeNumType;    //每个字符对应的字节数量
	int codeCur;         //当前第几个字符
	int startCur;        //行开头字符下标
	int endCur;          //行末尾下标
	// 输入框总内容
	std::string *m_pInputText;
	std::string inpuText; //当前输入框内容
public:
	CursorTextField();
	~CursorTextField();
	// static
	static CursorTextField* textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize);
	// CCLayer
	void onEnter();
	void onExit();
	bool init();
	// 初始化光标精灵
	void initCursorSprite(int nHeight);

	// CCTextFieldDelegate
	virtual bool onTextFieldAttachWithIME(CCTextFieldTTF *pSender);
	virtual bool onTextFieldDetachWithIME(CCTextFieldTTF * pSender);
	virtual bool onTextFieldInsertText(CCTextFieldTTF * pSender, const char * text, int nLen);
	virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * pSender, const char * delText, int nLen);

	// CCLayer Touch
	bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
	void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);

	// 判断是否点击在TextField处
	bool isInTextField(CCTouch *pTouch);
	// 得到TextField矩形
	CCRect getRect();

	// 打开输入法
	void openIME();
	// 关闭输入法
	void closeIME();

	const char* getInputText();
	void setInpuntText(char* text);
	void setInputWidth(float width);
	void setInputMaxLength(float length);

	int Utf82Unicode(LPWSTR out,  int outsize , LPSTR in,int insize);
};

#endif


cpp文件:

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

const static float DELTA = 0.5f;

using namespace cocos2d;
using namespace std;

CursorTextField::CursorTextField()
{
	CCTextFieldTTF();

	m_pCursorSprite = NULL;
	m_pCursorAction = NULL;

	m_pInputText = NULL;
	codeNumType = NULL;
}

CursorTextField::~CursorTextField()
{
	CC_SAFE_DELETE(m_pInputText);
	CC_SAFE_DELETE_ARRAY(codeNumType);
}

void CursorTextField::onEnter()
{
	CCTextFieldTTF::onEnter();
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,false);
	this->setDelegate(this);
}

CursorTextField * CursorTextField::textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize)
{
	CursorTextField *pRet = new CursorTextField();
	if(pRet && pRet->initWithString("", fontName, fontSize))
	{
		pRet->autorelease();
		if (placeholder)
		{
			pRet->setPlaceHolder(placeholder);
		}
		pRet->init();
		pRet->initCursorSprite(fontSize);
		pRet->setHorizontalAlignment(kCCTextAlignmentLeft);
		return pRet;
	}
	CC_SAFE_DELETE(pRet);
	return NULL;
}

bool CursorTextField::init(){
	this->inputFrameWidth = 400;
	this->inputMaxLength = 38;
	this->nLenCount = 0;
	this->codeNumType = new int[50];
	this->codeCur = 0;
	this->startCur = 0;
	this->endCur = 0;
	inpuText = "";
	return true;
}
void CursorTextField::initCursorSprite(const int mHeight)
{
	// 初始化光标
	const int column = 4;
	const int nHeight = (const int)mHeight;
	int pixels[25][column];
	for (int i=0; i<nHeight; ++i) {
		for (int j=0; j<column; ++j) {
			pixels[i][j] = 0xffffffff;
		}
	}
	CCTexture2D *texture = new CCTexture2D();
	texture->initWithData(pixels, kCCTexture2DPixelFormat_RGB888, 1, 1, CCSizeMake(column, nHeight));
	m_pCursorSprite = CCSprite::createWithTexture(texture);
	CCSize winSize = getContentSize();
	m_cursorPos = ccp(0, winSize.height / 2);
	m_pCursorSprite->setPosition(m_cursorPos);
	this->addChild(m_pCursorSprite);
	m_pCursorSprite->setVisible(false);
	m_pCursorAction = CCRepeatForever::create((CCActionInterval *) CCSequence::create(CCFadeOut::create(0.25f), CCFadeIn::create(0.25f), NULL));
	m_pCursorSprite->runAction(m_pCursorAction);
	m_pInputText = new std::string();
}

bool CursorTextField::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{    
	m_beginPos = pTouch->getLocation();
	return true;
}

CCRect CursorTextField::getRect()
{
	CCSize size = getContentSize();
	return  CCRectMake(0, -size.height / 2, inputFrameWidth, size.height);
}

//获取输入框内容
const char* CursorTextField::getInputText(){
	const char* text = m_pInputText->c_str();
	return text;
}

//设置输入框内容
void CursorTextField::setInpuntText(char* text){
	*m_pInputText = "";
    setString(text);
	m_pCursorSprite->setPositionX(0);
	CC_SAFE_DELETE_ARRAY(codeNumType);
	codeNumType = new int[50];
	codeCur = 0;
	startCur = 0;
	endCur = 0;
	inpuText = "";
}

//设置输入框宽度 一旦字符串宽度超度这个长度 字符串会自动向左缩进
void CursorTextField::setInputWidth(float width){
	this->inputFrameWidth = width;
}

//设置输入宽显示的最大字符数量Unicode
void CursorTextField::setInputMaxLength(float length){
	this->inputMaxLength = length;
}

//判断点击事件,是否响应在输入框范围内
bool CursorTextField::isInTextField(cocos2d::CCTouch *pTouch)
{
	return getRect().containsPoint(convertTouchToNodeSpaceAR(pTouch));
}

void CursorTextField::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
	CCPoint endPos = pTouch->getLocation();
	// 判断是否为点击事件
	if (::abs(endPos.x - m_beginPos.x) > DELTA || 
		::abs(endPos.y - m_beginPos.y)) 
	{
		// 不是点击事件
		m_beginPos.x = m_beginPos.y = -1;
		return;
	}

	// 判断是打开输入法还是关闭输入法
	isInTextField(pTouch) ? openIME() : closeIME();
}

//弹出手机键盘时响应事件
bool CursorTextField::onTextFieldAttachWithIME(cocos2d::CCTextFieldTTF *pSender)
{
	if (m_pInputText->empty()) {
		return false;
	}
	m_pCursorSprite->setPositionX(getContentSize().width);
	return false;
}

//当有输入进来时响应
//@param pSender 发送事件对象
//@param text 输入内容
//@param  内容字节长度
bool CursorTextField::onTextFieldInsertText(cocos2d::CCTextFieldTTF *pSender, const char *text, int nLen)
{
	std::string sText = m_pInputText->c_str();
	wchar_t* wText = new wchar_t[200];
	char t[200];
	memset(t,0,200);
	strcpy(t,sText.c_str());
	//将字符串转换为Unicode,并返回Unicode字符数量
	int cou = Utf82Unicode(wText,200,t,sText.length());
	//当字符数量超过规定值 不做处理
	if(cou >= inputMaxLength) return true;
	//屏蔽回车输入
	if(text[0] == '\n')
		return true;
	//输入框总内容添加
	m_pInputText->append(text);

	//测试
	CCLabelTTF* ttf = CCLabelTTF::create(text,"Verdana-Bold",26);
	float teWidth = ttf->getContentSize().width;
	CCLOG("any code length---%f",teWidth);

	//输入框当前字符串添加
	inpuText.append(text);
	//当前字符的长度
	codeNumType[codeCur++] = nLen;
	std::string* localText = m_pInputText;
	setString(m_pInputText->c_str());
	//如果总字符串的长度大于指定宽度
	if(getContentSize().width > inputFrameWidth){
	    //大于,截取字符串,直到字符串的长度小于指定宽度为止
		setString(inpuText.c_str());
		while(getContentSize().width > inputFrameWidth){
	    	int nnLen = nLen;
	    	if(codeNumType[startCur] == 1){
	    		nnLen = 1;
	    	}
    		if(codeNumType[startCur] == 3){
	    		nnLen = 3;
    		}
    		startCur++;
	    	nLenCount += nnLen;
	        float gap = localText->size() - nLenCount;
			inpuText = localText->substr(nLenCount,gap);
			setString(inpuText.c_str());
			float coWidth = getContentSize().width;
		}
	}
	else{
	    //小于,直接设置显示总字符串
		nLenCount = 0;
		startCur = 0;
		setString(m_pInputText->c_str());
	}
	//设置光标位置
	m_pCursorSprite->setPositionX(getContentSize().width);
	CC_SAFE_DELETE_ARRAY(wText);
	return true;
}


//当有输入进来时响应
//@param pSender 发送事件对象
//@param text 删除内容
//@param  内容字节长度
bool CursorTextField::onTextFieldDeleteBackward(cocos2d::CCTextFieldTTF *pSender, const char *delText, int nLen)
{
    //将总字符串长度减去nLen字节长
	m_pInputText->resize(m_pInputText->size() - nLen);
	//当前字符数减一
	codeNumType[codeCur--] = 0;
	std::string* localText = m_pInputText;
	setString(m_pInputText->c_str());
	if(getContentSize().width > inputFrameWidth){
	    //大于指定宽度,截取字符串,直到字符串长度小于指定宽度
		while(getContentSize().width > inputFrameWidth){
	    	int nnLen = nLen;
	    	if(codeNumType[startCur - 1] == 1){
	    		nnLen = 1;
	    	}
	    	if(codeNumType[startCur - 1] == 3){
	    		nnLen = 3;
	    	}
	    	nLenCount -= nnLen;
	    	startCur--;
    		if(startCur <=0)
	    		startCur = 0;
	    	if(nLenCount <=0 )
	    		nLenCount = 0;
	    	float gap = localText->size() - nLenCount;
	    	const std::string text = localText->substr(nLenCount,gap);
	    	setString(text.c_str());
			inpuText = text;
		}
	}
	else{
		nLenCount = 0;
		startCur = 0;
		setString(m_pInputText->c_str());
	}
	//设置光标位置
	m_pCursorSprite->setPositionX(getContentSize().width);
	if (m_pInputText->empty()) {
		m_pCursorSprite->setPositionX(0);
	}

	return true;
}

bool CursorTextField::onTextFieldDetachWithIME(cocos2d::CCTextFieldTTF *pSender)
{
	return false;
}

void CursorTextField::openIME()
{
	m_pCursorSprite->setVisible(true);
	this->attachWithIME();
}

void CursorTextField::closeIME()
{
	m_pCursorSprite->setVisible(false);
	this->detachWithIME();
}

void CursorTextField::onExit()
{
	CCTextFieldTTF::onExit();
	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}
int  CursorTextField::Utf82Unicode(LPWSTR out,  int outsize , LPSTR in,int insize)  
{  
    //-------------------------------------------------------------------------------------------  
    //参数有效性判断  
    if(out == NULL || in == NULL || insize<0)  
    {  
        return -1;  
    }  
	int typeCount = 0;
    int totalNum = 0;  
    char *p = in;  
    for(int i=0;i<insize;i++)  
    {  
        if (*p >= 0x00 && *p <= 0x7f)//说明最高位为'0',这意味着utf8编码只有1个字节!  
        {  
            p++;  
            totalNum += 1;  
        }  
        else if ((*p & (0xe0))== 0xc0)//只保留最高三位,看最高三位是不是110,如果是则意味着utf8编码有2个字节!  
        {  
            p++;  
            p++;  
            totalNum += 1;  
        }  
        else if ((*p & (0xf0))== 0xe0)//只保留最高四位,看最高三位是不是1110,如果是则意味着utf8编码有3个字节!  
        {  
            p++;  
            p++;  
            p++;  
            totalNum += 1;  
        }  
    }  
    if( outsize < totalNum )//参数有效性判断!  
    {  
        return -1;  
    }  
    //------------------------------------------------  
        int resultsize = 0;  
  
        p = in;  
        char* tmp = (char *)out;  
        while(*p)  
        {  
            if (*p >= 0x00 && *p <= 0x7f)//说明最高位为'0',这意味着utf8编码只有1个字节!  
            {  
                *tmp = *p;  
                tmp++;  
                //*tmp = '/0';  
                tmp++;  
                resultsize += 1;  
            }  
            else if ((*p & 0xe0)== 0xc0)//只保留最高三位,看最高三位是不是110,如果是则意味着utf8编码有2个字节!  
            {  
                wchar_t t = 0;  
                char t1 = 0;  
                char t2 = 0;  
  
                t1 = *p & (0x1f);//高位的后5位!(去除了头部的110这个标志位)  
                p++;  
                t2 = *p & (0x3f);//低位的后6位!(去除了头部的10这个标志位)  
  
                *tmp = t2 | ((t1 & (0x03)) << 6);  
                tmp++;  
                *tmp = t1 >> 2;//留下其保留的三位  
                tmp++;  
                resultsize += 1;  
            }  
            else if ((*p & (0xf0))== 0xe0)//只保留最高四位,看最高三位是不是1110,如果是则意味着utf8编码有3个字节!  
            {  
                wchar_t t = 0;  
                wchar_t t1 = 0;  
                wchar_t t2 = 0;  
                wchar_t t3 = 0;  
                t1 = *p & (0x1f);  
                p++;  
                t2 = *p & (0x3f);  
                p++;  
                t3 = *p & (0x3f);  
  
                *tmp = ((t2 & (0x03)) << 6) | t3;  
                tmp++;  
                *tmp = (t1 << 4) | (t2 >> 2);  
                tmp++;  
                resultsize += 1;  
            }  
            p++;  
        }  
        /*不考虑结束符,如果考虑则打开此段!  
        *tmp = '/0';  
        tmp++;  
        *tmp = '/0';  
        resultsize += 2;  
        */  
        return resultsize;  
}  

上面代码是通是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、付费专栏及课程。

余额充值