CCControlColourPicker實現(xiàn)顏色拾取器的功能。關(guān)于控件使用時的一些配置,請參見文章:UI開發(fā)之控件類-CCControlButton。下邊來看源代碼。
- bool HelloWorld::init()
- {
- bool bRet = false;
- do
- {
- CC_BREAK_IF(! CCLayer::init());
- //設(shè)置一個顯示字符串的label
- CCLabelTTF * title = CCLabelTTF::create("#128128128","Arial",32);
- title->setPosition(ccp(240,280));
- //設(shè)置label的tag為1,方便以后獲取
- this->addChild(title,0,1);
- //這里有一個問題需要注意,在create之前,應(yīng)該在resource目錄下新建一個文件夾叫做extensions,然后把源代碼中
- //和CCControlColourPicker相關(guān)的資源導(dǎo)入進(jìn)去
- CCControlColourPicker * colorPicker = CCControlColourPicker::create();
- colorPicker->setColor(ccc3(128,128,128));
- //設(shè)置一張背景圖片,但是卻不起作用,至今沒解決,有誰解決了,說一聲
- //colorPicker->setBackground(CCSprite::create("HelloWorld.png"));
- //為colorPicker添加事件監(jiān)聽函數(shù)
- colorPicker->addTargetWithActionForControlEvents(this,cccontrol_selector(HelloWorld::colorValueChanged),
- CCControlEventValueChanged);
- //設(shè)置位置
- colorPicker->setPosition(ccp(240,160));
- this->addChild(colorPicker);
- bRet = true;
- } while (0);
- return bRet;
- }
- void HelloWorld::colorValueChanged(CCObject * pSender,CCControlEvent controlEvent)
- {
- CCLabelTTF * title = (CCLabelTTF *)this->getChildByTag(1);
- CCControlColourPicker * pPicker = (CCControlColourPicker *)pSender;
- //這里需要注意了,本人用的cocos2d-x的版本是2.2,應(yīng)該用pPicker調(diào)用getColor函數(shù),但據(jù)本人查看他人的
- //博客,他們都是用的getColorValue函數(shù),他們應(yīng)該是早一點的版本
- title->setString(CCString::createWithFormat("#%03d%03d%03d",pPicker->getColor().r,pPicker->getColor().g,
- pPicker->getColor().b)->getCString());
- }