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