Cocos2d-x 3.9教程:
7. Cocos2d-x中的控件
1.1. Button
按钮的使用,详见“4.4按钮的基本使用及9宫格缩放”。
1.2. 旋钮控件ControlPotentiometer
旋钮控件,由“底座图片”、“进度条图片”和“控制按钮图片”3部分组成。如下图:
在界面上的最终效果:
初始状态:
拖动时状态:
具体代码如下:
ControlPotentiometer * potentiometer = ControlPotentiometer::create("potentiometerTrack.png",
"potentiometerProgress.png", "potentiometerButton.png");
potentiometer->setPosition(Vec2(100, 200));
this->addChild(potentiometer);
注意,此类控件需要添加扩展库的支持:
#include "cocos-ext.h"
USING_NS_CC_EXT;
若编译时提示: fatal error C1083: 无法打开包括文件:“extensions/ExtensionMacros.h: No such file or directory”。
则还需要在项目属性上附加包含目录:
选中工程右键“属性”->"配置属性“->"c/c++"->"常规”->"附加包含目录"中添加“”$(EngineRoot)
添加响应事件:
ControlPotentiometer * potentiometer = ControlPotentiometer::create("potentiometerTrack.png",
"potentiometerProgress.png", "potentiometerButton.png");
potentiometer->setPosition(Vec2(100, 200));
potentiometer->addTargetWithActionForControlEvents(this, cccontrol_selector(HelloWorld::onValueChanged), Control::EventType::VALUE_CHANGED);
this->addChild(potentiometer);
auto showValue = Label::createWithTTF(G2U("数值:"), "fonts/abc.ttf", 24);
showValue->setTextColor(Color4B::WHITE);
showValue->setTag(1);
showValue->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
this->addChild(showValue, 1);
void HelloWorld::onValueChanged(Ref* pSender, Control::EventType event)
{
ControlPotentiometer * potentiometer = (ControlPotentiometer*)pSender;
String *valueStr = String::createWithFormat("数值:%f", potentiometer->getValue());
Label * label = (Label*)getChildByTag(1);
label->setString(G2U(valueStr->getCString()));
}
1.3. 滑条控件-血量条ControlSlider
跟旋钮控件类似,滑条空间也是由3部分组成:“背景图片”、“进度条图片”和“控制按钮图片”。如果把“控制按钮”设为透明的,则变成了游戏中的“血槽”,类似于进度条的效果。
创建和响应事件的方式也非常的类似:
#include "cocos-ext.h"
USING_NS_CC_EXT;
ControlSlider * slider = ControlSlider::create("sliderBg.png",
"sliderValue.png", "button.png");
slider->setPosition(Vec2(100, 200));
slider->setMinimumValue(0);
slider->setMaximumValue(5000);
slider->setValue(3000);
slider->addTargetWithActionForControlEvents(this, cccontrol_selector(HelloWorld::onValueChanged), Control::EventType::VALUE_CHANGED);
this->addChild(slider);
auto showValue = Label::createWithTTF(G2U("数值:"), "fonts/abc.ttf", 24);
showValue->setTextColor(Color4B::WHITE);
showValue->setTag(1);
showValue->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
this->addChild(showValue, 1);
void HelloWorld::onValueChanged(Ref* pSender, Control::