Cocos2d-X中SwitchControl的用法

前端之家收集整理的这篇文章主要介绍了Cocos2d-X中SwitchControl的用法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

SwitchControl控件起到了一个开关的作用类似于现实生活中的开关

由于控件比较简单,我就不做过多的解释,直接上代码


首先在工程目录下的Resource文件夹中添加三张图片


在SwitchControl.h添加下面代码

  1. #ifndef _SwitchControl_H_
  2. #define _SwitchControl_H_
  3.  
  4. #include "cocos2d.h"
  5. #include "cocos-ext.h"
  6. USING_NS_CC;
  7. USING_NS_CC_EXT;
  8.  
  9. class SwitchControl : public CCLayer
  10. {
  11. public:
  12. static CCScene* scene();
  13. CREATE_FUNC(SwitchControl);
  14. bool init();
  15. void switchValueChanged(CCObject*,CCControlEvent);
  16. };
  17.  
  18. #endif


在SwitchControl.cpp中添加下面代码

  1. #include "SwitchControl.h"
  2.  
  3. CCScene* SwitchControl::scene()
  4. {
  5. CCScene* s = CCScene::create();
  6. SwitchControl* layer = SwitchControl::create();
  7. s->addChild(layer);
  8. return s;
  9. }
  10.  
  11. bool SwitchControl::init()
  12. {
  13. CCLayer::init();
  14.  
  15. //得到窗口的大小
  16. CCSize winSize = CCDirector::sharedDirector()->getWinSize();
  17.  
  18. //设置ControlSwitch控件打开的文字No"
  19. CCLabelTTF* on = CCLabelTTF::create("ON","Arial",16);
  20. //设置ControlSwitch控件关闭时的文字"OFF"
  21. CCLabelTTF* off = CCLabelTTF::create("OFF",16);
  22. //设置ControlSwitch控件打开的文字的颜色
  23. on->setColor(ccc3(0,0));
  24.  
  25. //设置ControlSwitch控件关闭时的颜色
  26. off->setColor(ccc3(0,0));
  27.  
  28. //创建ControlSwitch控件
  29. CCControlSwitch* control = CCControlSwitch::create(
  30. CCSprite::create("switch-mask.png"),CCSprite::create("switch-on.png"),CCSprite::create("switch-off.png"),CCSprite::create("switch-thumb.png"),on,off);
  31.  
  32. //添加ControlSwitch控件
  33. addChild(control);
  34. //设置ControlSwitch控件的位置
  35. control->setPosition(ccp(winSize.width / 2,winSize.height / 2));
  36.  
  37. // 注册valuechange消息,当valuechange时,调用switchValueChanged函数
  38. control->addTargetWithActionForControlEvents(this,cccontrol_selector(SwitchControl::switchValueChanged),CCControlEventValueChanged);
  39. return true;
  40. }
  41.  
  42. void SwitchControl::switchValueChanged(CCObject* sender,CCControlEvent ev)
  43. {
  44. if (ev == CCControlEventValueChanged)
  45. {
  46. CCControlSwitch* control = (CCControlSwitch*)sender;
  47. if (control->isOn())
  48. {
  49. CCLog("Switch if ON");
  50. }
  51. else
  52. {
  53. CCLog("Swith is Off");
  54. }
  55. }
  56. else
  57. {
  58. CCLog("other events");
  59. }
  60. }

执行结果:


演示效果




猜你在找的Cocos2d-x相关文章