Usage of SwitchControl in Cocos2d-X
The SwitchControl controls act as switches in real life.
Since the control is relatively simple, I will not explain it too much and directly go to the code
First, add three images to the Resource folder under the project directory.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + expires + CjxwcmUgY2xhc3M9 "brush: java;"> # 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
Add the following code to 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 (); // obtain the window size. CCSize winSize = CCDirector :: sharedDirector ()-> getWinSize (); // set the text opened by the ControlSwitch control to No "CCLabelTTF * on = CCLabelTTF: create (" ON "," Arial ", 16 ); // set the text "OFF" CCLabelTTF * off = CCLabelTTF: create ("OFF", "Arial", 16) when the ControlSwitch control is disabled ); // set the color of the text opened by the ControlSwitch control on-> setColor (ccc3 (0, 0, 0 )); // set the color off when the ControlSwitch control is disabled-> setColor (ccc3 (0, 0, 0); // create the ControlSwitch control 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); // Add the ControlSwitch control addChild (control); // set the position of the ControlSwitch control-> setPosition (ccp (winSize. width/2, winSize. height/2); // register the valuechange message. When valuechange occurs, call the switchValueChanged function 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 ");}}
Execution result:
Demo effect:
Zookeeper