cocos2d-x2.2.6 之CCControlButton的使用方法

偶在今天想通过某一个按钮的按下松开实现针对于某一个动画的切换,之前使用的CCMenuItemImage,大概代码如下:

// 使用图片创建按钮
CCMenuItemImage *pFightItem = CCMenuItemImage::create(
        "Normal.png",        // 正常图片
        "Selected.png",      // 按下图片
        this,
        menu_selector(SecondScene::menuFightCallback));   // 回调接口

// 设定位置
pFightItem->setPosition(ccp(400 ,200));

CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition(CCPointZero);
this->addChild(pMenu, 1);        

然后查各种资料,未查到关于CCMenuItemImage 关于按钮状态的设定,虽然可以使用UIButton中的ToucheEventType来获取按钮的不同状态,但是我觉得cocos2d-x还应该有其它的方法,那就是使用:CCControlButton

大概的代码如下:

#include "cocos-ext.h"
using namespace cocos2d::extension;

    // 按钮文字
    CCLabelTTF *title = CCLabelTTF::create("Fight","Market Felt",20);    
    // 正常状态图片
    CCScale9Sprite* btnNormal = CCScale9Sprite::create("CloseNormal.png");
    // 按下状态图片
    CCScale9Sprite* btnDown = CCScale9Sprite::create("CloseSelected.png");        

    // 创建按钮(共有四种方式,大家自行查看代码参考)
    CCControlButton* Btn = CCControlButton::create(title,btnNormal);    
    // 设置按钮按下时的图片
    Btn->setBackgroundSpriteForState(btnDown,CCControlStateSelected);
    // 设置按钮按下时文字的状态
    Btn->setTitleColorForState(ccYELLOW,CCControlStateHighlighted);        
    Btn->setPosition(ccp(400 ,200));
    this->addChild(Btn);

   // 设置按钮按下事件
    Btn->addTargetWithActionForControlEvents(this, cccontrol_selector(SecondScene::touchDown), CCControlEventTouchDown);

  // 设置按钮松开事件
    Btn->addTargetWithActionForControlEvents(this, cccontrol_selector(SecondScene::touchUpInside), CCControlEventTouchUpInside);

针对于CCControlButton的状态,共有如下几种:

enum 
{
  // 鼠标按下按钮,触发
    CCControlEventTouchDown            = 1 << 0,  

    // 鼠标按下按钮,且在按钮范围内不曾松开,触发
    CCControlEventTouchDragInside     = 1 << 1, 

    // 鼠标按下按钮,离开按钮范围且不曾松开,触发  
    CCControlEventTouchDragOutside   = 1 << 2,  
    CCControlEventTouchDragEnter      = 1 << 3,    
    CCControlEventTouchDragExit        = 1 << 4,  

    // 鼠标按下按钮,在按钮范围内松开,触发
    CCControlEventTouchUpInside        = 1 << 5,  

    // 鼠标按下按钮,在按钮范围外松开,触发
    CCControlEventTouchUpOutside     = 1 << 6,   
    CCControlEventTouchCancel        = 1 << 7,    
    CCControlEventValueChanged       = 1 << 8      
};
typedef unsigned int CCControlEvent;

你可能感兴趣的:(cocos2d-x2.2.6 之CCControlButton的使用方法)