1. Button 的创建
(1)Button的创建 create方法
Button::create()
Button::create(const std::string &normalImage,const std::string& selectedImage , const std::string& disableImage, TextureResType texType)
normalImage:正常状态的纹理贴图
selectedImage : 选中状态的纹理贴图
disableImage:禁用状态的纹理贴图
(2)拉伸图片
btn->setScale9Enabled(true) 打开scale9 可以拉伸图片,类似android 中9.png的图片
Size visibleSize = Director::getInstance()->getVisibleSize();
//创建button对象
auto btn = Button::create("button.png","buttonHighlighted.png");
//打开scale9 可以拉伸图片
btn->setScale9Enabled(true);
//设置button title
btn->setTitleText("Jump");
//设置button title字体大小
btn->setTitleFontSize(35);
//设置btn的内容大小
btn->setContentSize(Size(100,50));
//设置btn的位置
btn->setPosition(Vec2(visibleSize.width-100,50));
//为按钮添加触摸事件监听
btn->addTouchEventListener(CC_CALLBACK_2(TollgateScene::jumpEvent,this));
this->addChild(btn,4);
2. 按钮的监听事件
//为按钮添加触摸事件监听
btn->addTouchEventListener(CC_CALLBACK_2(TollgateScene::jumpEvent,this));
其中 TouchEventType有四个值:
BEGAN :按钮按下的type
MOVED: 按钮按下并移动
ENDED:按钮结束按下的type
CANCELED:按钮中断的type
void UIButtonTest_Editor::touchEvent(Ref *pSender, Widget::TouchEventType type)
{
switch (type)
{
case Widget::TouchEventType::BEGAN:
_displayValueLabel->setString("Touch Down");
break;
case Widget::TouchEventType::MOVED:
_displayValueLabel->setString("Touch Moved");
break;
case Widget::TouchEventType::ENDED:
_displayValueLabel->setString("Touch Ended");
break;
case Widget::TouchEventType::CANCELED:
_displayValueLabel->setString("Touch Canceled");
break;
default:
break;
}
}