標籤:style blog http color io os ar for 檔案
SwitchControl控制項起到了一個開關的作用類似於現實生活中的開關
由於控制項比較簡單,我就不做過多的解釋,直接上代碼
首先在工程目錄下的Resource檔案夾中添加三張圖片
在SwitchControl.h添加下面代碼
#ifndef _SwitchControl_H_#define _SwitchControl_H_#include "cocos2d.h"#include "cocos-ext.h"USING_NS_CC;USING_NS_CC_EXT;class SwitchControl : public CCLayer {public: static CCScene* scene();CREATE_FUNC(SwitchControl);bool init();void switchValueChanged(CCObject*, CCControlEvent);};#endif
在SwitchControl.cpp中添加下面代碼
#include "SwitchControl.h"CCScene* SwitchControl::scene(){CCScene* s = CCScene::create();SwitchControl* layer = SwitchControl::create();s->addChild(layer);return s;}bool SwitchControl::init(){ CCLayer::init(); //得到視窗的大小 CCSize winSize = CCDirector::sharedDirector()->getWinSize(); //設定ControlSwitch控制項開啟的文字No"CCLabelTTF* on = CCLabelTTF::create("ON", "Arial", 16); //設定ControlSwitch控制項關閉時的文字"OFF" CCLabelTTF* off = CCLabelTTF::create("OFF", "Arial", 16); //設定ControlSwitch控制項開啟的文字的顏色 on->setColor(ccc3(0, 0, 0)); //設定ControlSwitch控制項關閉時的顏色off->setColor(ccc3(0, 0, 0)); //建立ControlSwitch控制項 CCControlSwitch* control = CCControlSwitch::create( CCSprite::create("switch-mask.png"), CCSprite::create("switch-on.png"), CCSprite::create("switch-off.png"), CCSprite::create("switch-thumb.png"), on, off); //添加ControlSwitch控制項 addChild(control); //設定ControlSwitch控制項的位置 control->setPosition(ccp(winSize.width / 2, winSize.height / 2));// 註冊valuechange訊息,當valuechange時,調用switchValueChanged函數control->addTargetWithActionForControlEvents(this, cccontrol_selector(SwitchControl::switchValueChanged), CCControlEventValueChanged);return true;}void SwitchControl::switchValueChanged(CCObject* sender, CCControlEvent ev){if (ev == CCControlEventValueChanged){CCControlSwitch* control = (CCControlSwitch*)sender;if (control->isOn()){CCLog("Switch if ON");}else{CCLog("Swith is Off");}}else{CCLog("other events");}}
執行結果:
示範效果:
Cocos2d-X中SwitchControl的用法