Cocos2d-x UI以及控件

#include "HelloWorldScene.h"


HelloWorld::HelloWorld()
{


}




HelloWorld::~HelloWorld()
{


}
Scene* HelloWorld::createScene()
{
    auto scene = Scene::create();
    auto layer = HelloWorld::create();
    scene->addChild(layer);
    return scene;
}


bool HelloWorld::init()
{


    if ( !Layer::init() )
    {
        return false;
    }
    
auto visibleSize = Director::getInstance()->getVisibleSize();
/************************************************************************/
/*       Sprite                               */
/************************************************************************/
Sprite* pLayerBg = Sprite::create("123.png");
//Sprite* pLayerBg = Sprite::createWithSpriteFrameName("123.png");
pLayerBg->setPosition(Vec2(480.f, 320.f));
pLayerBg->setAnchorPoint(Vec2(0.f, 1.f));
pLayerBg->setTextureRect(Rect(0,0,100,100));
pLayerBg->setScaleX(200.f / pLayerBg->getContentSize().width);//宽200;
pLayerBg->setScaleY(200.f / pLayerBg->getContentSize().height);//高200;
pLayerBg->setScale(0.8f);
pLayerBg->setVisible(true);
pLayerBg->setZOrder(1);
pLayerBg->setCascadeOpacityEnabled(true);//打开透明度;
pLayerBg->setOpacity(123);
pLayerBg->setTexture("OtherImage.bundle/Champion/cp_equip_0.png");//本地文件获取;
pLayerBg->setSpriteFrame("123.png");//参数为spriteFrameName   plist文件获取;
pLayerBg->setSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("132.png"));//参数为spriteFrame   plist文件获取;等价于Sprite::createWithSpriteFrameName("123.png");
//pLayerBg->setSpriteFrame(Sprite::create("OtherImage.bundle/Champion/cp_equip_0.png")->getSpriteFrame());//参数为spriteFrame   本地文件获取;
this->addChild(pLayerBg, 0);
pLayerBg->runAction(RepeatForever::create(RotateBy::create(2.f, 360)));
pLayerBg->removeFromParentAndCleanup(true);
pLayerBg = NULL;
pLayerBg->stopAllActions();
pLayerBg->setRotation(0.f);
bool isEqual = pLayerBg->getResourceName().compare("123.png") != 0;
Rect tempRc = pLayerBg->getTextureRect();


/************************************************************************/
/*       Label                              */
/************************************************************************/
auto _labelDownStatus = Label::create("", "Arial", 20);
//auto _labelDownStatus = Label::create("", "", 20, Size(800.f, 150.f), TextHAlignment::LEFT, TextVAlignment::TOP);
_labelDownStatus->setColor(Color3B::YELLOW);
_labelDownStatus->setTextColor(Color4B::YELLOW);
_labelDownStatus->setString("1323");
_labelDownStatus->setOpacity(120);
_labelDownStatus->enableShadow(Color4B(0, 0, 0, 100), Size(1, -1));
_labelDownStatus->enableOutline(Color4B(0, 40, 50, 255), 2);
_labelDownStatus->setPosition(Vec2(480.f, 120.f));
_labelDownStatus->setMaxLineWidth(140);
_labelDownStatus->setDimensions(480, 80);
_labelDownStatus->setLineBreakWithoutSpace(false);
_labelDownStatus->setWidth(500);
_labelDownStatus->setRotationSkewY(180.f);
_labelDownStatus->setAlignment(TextHAlignment::CENTER, TextVAlignment::CENTER);
_labelDownStatus->setVerticalAlignment(TextVAlignment::CENTER);
_labelDownStatus->setHorizontalAlignment(TextHAlignment::CENTER);
this->addChild(_labelDownStatus, 2);
_labelDownStatus->runAction(Sequence::create(DelayTime::create(3.f), RemoveSelf::create(), NULL));


/************************************************************************/
/*       Label                              */
/************************************************************************/


//字体数字;
auto textatlas = Label::createWithCharMap("OtherImage.bundle/Num/public_num.png", 30, 34, ',');
textatlas->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
textatlas->setSkewX(15);
textatlas->setPosition(Vec2(650, 35));
this->addChild(textatlas);
/************************************************************************/
/*       LabelAtlas                              */
/************************************************************************/
//字体数字;
auto scoreLabel = LabelAtlas::create("0","OtherImage.bundle/Num/Desk_Score_Num.png", 38, 60, '/');
scoreLabel->setAnchorPoint(Vec2(0.5f, 0.5f));
scoreLabel->setScale(0.5f);
scoreLabel->setPosition(_labelDownStatus->getPosition());
this->addChild(scoreLabel, 15);




/************************************************************************/
/*       ProgressTimer                       */
/************************************************************************/


auto _downProgress = ProgressTimer::create(Sprite::create("1132.png"));
_downProgress->setType(ProgressTimer::Type::BAR);
_downProgress->setPosition(Vec2(480.f, 80.f));
_downProgress->setMidpoint(Vec2(0, 0));
_downProgress->setBarChangeRate(Vec2(1, 0));
_downProgress->setReverseDirection(true);
_downProgress->setPercentage(0);
this->addChild(_downProgress, 2);


_downProgress->runAction(Sequence::create(ProgressFromTo::create(10.f, 20, 30), NULL));//从哪里滚动到哪里;
_downProgress->runAction(Sequence::create(ProgressTo::create(10.f,30), NULL));//滚动到哪里;


/************************************************************************/
/*       Scale9Sprite                       */
/************************************************************************/
auto _loadBg = ui::Scale9Sprite::createWithSpriteFrameName("Public_Tip_Bg.png");
//auto _loadBg = ui::Scale9Sprite::create("OtherImage.bundle/OtherImg/Eq_Black.png", Rect(0, 0, 50, 50), Rect(20, 20, 10, 10));
_loadBg->setCapInsets(Rect(30.f, 30.f, 40.f, 40.f));
_loadBg->setContentSize(Size(100.f, 46.f));
_loadBg->setPosition(Vec2(480.f, 100.f));
this->addChild(_loadBg, 0);




/************************************************************************/
/*       MenuItemSprite                       */
/************************************************************************/
ui::Scale9Sprite* bt1Normal = ui::Scale9Sprite::createWithSpriteFrameName("p_green_btn_n.png");
bt1Normal->setContentSize(Size(240.f, 66.f));
ui::Scale9Sprite* bt1Press = ui::Scale9Sprite::createWithSpriteFrameName(("p_green_btn_p.png"));
bt1Press->setContentSize(Size(240.f, 66.f));
//Sprite* bt1Normal = Sprite::createWithSpriteFrameName("p_green_btn_n.png");
//Sprite* bt1Press = Sprite::createWithSpriteFrameName(("p_green_btn_p.png"));
//第一种;
MenuItemSprite* offlineMenu = MenuItemSprite::create(bt1Normal, bt1Press, CC_CALLBACK_1(HelloWorld::menuCallBack, this));
offlineMenu->setAnchorPoint(Vec2(1.f, 1.f));
offlineMenu->setPosition(Vec2(480.f,320.f));
//offlineMenu->setNormalImage(Sprite::createWithSpriteFrameName("DeskGame_Cue_Small_Normal.png"));
//offlineMenu->setSelectedImage(Sprite::createWithSpriteFrameName("DeskGame_Cue_Small_Press.png"));
offlineMenu->setEnabled(false);
offlineMenu->selected();
//offlineMenu->setEnabled(true);
//offlineMenu->unselected();


auto _TopMenu = Menu::createWithItem(offlineMenu);
_TopMenu->setPosition(Vec2(0.f, 300.f));
this->addChild(_TopMenu);


//第二种;
Vector itemArray;
MenuItemSprite* guestMenu = MenuItemSprite::create(bt1Normal, bt1Press, CC_CALLBACK_1(HelloWorld::menuCallBack, this));
itemArray.pushBack(guestMenu);


MenuItemSprite* dingNiuMenu = MenuItemSprite::create(bt1Normal, bt1Press, CC_CALLBACK_1(HelloWorld::menuCallBack, this));
itemArray.pushBack(dingNiuMenu);


auto _bottomMenu = Menu::createWithArray(itemArray);
_bottomMenu->alignItemsHorizontallyWithPadding(20.f);
_bottomMenu->setPosition(Vec2(0.f, 300.f));
this->addChild(_bottomMenu);


//第三种;
MenuItemSprite* guestMenu = MenuItemSprite::create(bt1Normal, bt1Press, CC_CALLBACK_1(HelloWorld::menuCallBack, this));
MenuItemSprite* dingNiuMenu = MenuItemSprite::create(bt1Normal, bt1Press, CC_CALLBACK_1(HelloWorld::menuCallBack, this));


auto _bottomMenu = Menu::create(guestMenu,dingNiuMenu,NULL);
_bottomMenu->alignItemsHorizontallyWithPadding(20.f);
_bottomMenu->setPosition(Vec2(0.f, 300.f));
this->addChild(_bottomMenu);




/************************************************************************/
/*       MenuItemLabel                       */
/************************************************************************/
//俱乐部名称;
auto nameMenu = MenuItemLabel::create(Label::create("123", "Arial", 22), CC_CALLBACK_1(HelloWorld::menuCallBack, this));
nameMenu->setPosition(20 + nameMenu->getContentSize().width / 2.f, 100);
nameMenu->setColor(Color3B(0xbd, 0x94, 0x60));
nameMenu->setTag(1);
auto btMenu = Menu::create(nameMenu, NULL);
btMenu->setPosition(Vec2::ZERO);
this->addChild(btMenu);




/************************************************************************/
/*       MenuItemToggle                       */
/************************************************************************/
auto soundOnMenuItem = MenuItemImage::create("on.png", "on.png");
auto soundOffMenuItem = MenuItemImage::create("off.png", "off.png");
auto soundToggleMenuItem = MenuItemToggle::createWithCallback(
CC_CALLBACK_1(HelloWorld::menuCallBack, this), soundOnMenuItem, soundOffMenuItem, NULL);     soundToggleMenuItem->setPosition(Director::getInstance()->convertToGL(Point(818, 220)));
Menu* mn = Menu::create(soundToggleMenuItem, NULL);
mn->setPosition(Point::ZERO);


/************************************************************************/
/*       MenuItemFont                       */
/************************************************************************/
MenuItemFont::setFontName("Courier New"); // 设置字体;
MenuItemFont::setFontSize(64);  // 设置大小;
// 创建MenuItemFont菜单项,第一个参数是菜单项中显示的文字内容,第二个参数是玩家点击时调用的回调函数。;
auto fontItem = MenuItemFont::create("MenuItemFont", CC_CALLBACK_1(HelloWorld::
menuCallBack, this));
fontItem->setPosition(visibleSize.width / 2, visibleSize.height*0.7);
auto menu = Menu::create(fontItem, NULL);
// 设置菜单项在屏幕的位置;
menu->setPosition(Vec2::ZERO);
// 将菜单添加到当前层的子节点;
this->addChild(menu);


/************************************************************************/
/*       MenuItemImage                       */
/************************************************************************/
// ④图片菜单项(MenuItemImage)的使用
// 创建MenuItemImage菜单项,
// 第一个参数是正常状态的纹理图片,第二个参数是选择状态下的纹理图片,第三个参数是回调函数。
// 关闭菜单;
auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
closeItem->setPosition(Vec2(480.f,320.f));
auto menu = Menu::create(fontItem, NULL);
// 设置菜单项在屏幕的位置;
menu->setPosition(Vec2::ZERO);
// 将菜单添加到当前层的子节点;
this->addChild(menu);


/************************************************************************/
/*       Layer                               */
/************************************************************************/
auto _loadResLayer = Layer::create();
_loadResLayer->setPosition(Point::ZERO);
addChild(_loadResLayer, 10);


/************************************************************************/
/*       LayerColor                               */
/************************************************************************/
//添加颜色层;
auto layerblack = LayerColor::create(Color4B::BLACK);
layerblack->setContentSize(Size(1136.f, 720.f));
layerblack->setIgnoreAnchorPointForPosition(false);//忽略锚点为(0,0,);
layerblack->setPosition(Vec2(480.f, 320.f));
this->addChild(layerblack, -1);




/************************************************************************/
/*       Layout                       */
/************************************************************************/
// 创建Layout
Layout* layout_Left = Layout::create();
// 设置Layout的布局类型为平面相对布局
layout_Left->setLayoutType(LayoutType::RELATIVE);
// 设置Layout的ContentSize
layout_Left->setContentSize(Size(280, 150));
// 设置Layout的锚点
layout_Left->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
// 设置Layout的背景颜色类型为单一固定颜色
layout_Left->setBackGroundColorType(Layout::BackGroundColorType::SOLID);
// 设置Layout的背景颜色为绿色
layout_Left->setBackGroundColor(Color3B::GREEN);
// 设置Layout的位置
layout_Left->setPosition(Vec2(100, visibleSize.height / 2));
// 将Layout添加为当前层的子节点
this->addChild(layout_Left);
// 创建一个Button对象,设置在Layout的左上角
Button* button_TopLeft = Button::create("animationbuttonnormal.png",
"animationbuttonpressed.png");
layout_Left->addChild(button_TopLeft);
RelativeLayoutParameter* rp_TopLeft = RelativeLayoutParameter::create();
/*PARENT_TOP_LEFT左上角PARENT_TOP_CENTER_HORIZONTAL上方中间位置
PARENT_TOP_RIGHT右上角PARENT_LEFT_CENTER_VERTICAL中间左边
CENTER_IN_PARENT中间PARENT_RIGHT_CENTER_VERTICAL中间右边
PARENT_LEFT_BOTTOM底端左边PARENT_BOTTOM_CENTER_HORIZONTAL底端中间PARENT_RIGHT_BOTTOM底端右边*/
rp_TopLeft->setAlign(RelativeLayoutParameter::RelativeAlign::PARENT_TOP_LEFT);
button_TopLeft->setLayoutParameter(rp_TopLeft);




/************************************************************************/
/*       Button                       */
/************************************************************************/
Button* pBtnClose = Button::create("cp_eq_close_n.png", "cp_eq_close_p.png", "", ui::Widget::TextureResType::PLIST);
//pBtnClose->addClickEventListener(CC_CALLBACK_1(HelloWorld::bttCallBack, this));//addClickEventListener没有触摸开始和结束;
pBtnClose->addTouchEventListener(CC_CALLBACK_2(HelloWorld::buttonCallBack, this));//addTouchEventListener有触摸开始和结束;
//pBtnClose->addTouchEventListener(Widget::ccWidgetTouchCallback(CC_CALLBACK_2(HelloWorld::onImageViewCallback, this)));
pBtnClose->loadTextures("cp_ls_play_n_tw.png", "cp_ls_play_p_tw.png", "", ui::Widget::TextureResType::PLIST);
pBtnClose->setCapInsets(Rect(25, 25, 8, 8));
pBtnClose->setScale9Enabled(true);
pBtnClose->setContentSize(Size(144.f, 55.f));
pBtnClose->setTitleFontName("Arial");
pBtnClose->setTitleFontSize(20);
pBtnClose->setTitleText("adgfgg");
pBtnClose->setPosition(Vec2(540.f, 470.f));
pBtnClose->loadTextureNormal("123.png", ui::Widget::TextureResType::PLIST);
pBtnClose->loadTexturePressed("123.png", ui::Widget::TextureResType::PLIST);
pBtnClose->loadTextureDisabled("p_gray_btn_n.png", ui::Widget::TextureResType::PLIST);
pBtnClose->setPressedActionEnabled(false);//设置启用按钮被按下时的缩放操作;
this->addChild(pBtnClose);


Label* label = pBtnClose->getTitleRenderer();//按钮上的字,与setTitleText结合使用;
label->disableEffect(LabelEffect::SHADOW);
label->setColor(Color3B::GRAY);
label->enableShadow(Color4B::BLACK, Size(1, -1));


pBtnClose->setTouchEnabled(false);
pBtnClose->setBright(false);
//pBtnClose->setTouchEnabled(true);
//pBtnClose->setBright(true);
pBtnClose->setBrightStyle(Widget::BrightStyle::HIGHLIGHT);
pBtnClose->setEnabled(false);
//pBtnClose->setBrightStyle(Widget::BrightStyle::NORMAL);
//pBtnClose->setEnabled(true);


//pBtnClose->addTouchEventListener([=](Ref* pSender, Widget::TouchEventType type){
// switch (type) {
// case Widget::TouchEventType::BEGAN:
// label->setString("触摸事件类型:BEGAN");
// break;
// case Widget::TouchEventType::MOVED:
// label->setString("触摸事件类型:MOVED");
// break;
// case Widget::TouchEventType::ENDED:
// label->setString("触摸事件类型:ENDED");
// break;
// case Widget::TouchEventType::CANCELED:
// label->setString("触摸事件类型:CANCELED");
// break;
// default:
// break;
// }
//});


/************************************************************************/
/*       ImageView                               */
/************************************************************************/
ImageView* pImgIcon = ImageView::create();
pImgIcon->setPosition(Vec2(0.f, 10.f));
pImgIcon->setScale9Enabled(true);
pImgIcon->setContentSize(Size(940.f,200.f));
pImgIcon->loadTexture("OtherImage.bundle/OtherImg/CueLayer_Bg.png", ui::Widget::TextureResType::PLIST);
pImgIcon->setTouchEnabled(false);
pImgIcon->setBright(false);
//pImgIcon->addClickEventListener(CC_CALLBACK_1(HelloWorld::bttCallBack, this));//addClickEventListener没有触摸开始和结束;
pImgIcon->addTouchEventListener(Widget::ccWidgetTouchCallback(CC_CALLBACK_2(HelloWorld::onImageViewCallback, this)));
this->addChild(pImgIcon);
pImgIcon->setBrightStyle(Widget::BrightStyle::HIGHLIGHT);
pImgIcon->setEnabled(false);


//pImgIcon->setBrightStyle(Widget::BrightStyle::NORMAL);
//pImgIcon->setEnabled(true);


/************************************************************************/
/*       Text                              */
/************************************************************************/
Text* pLabelScore = Text::create("132", "", 17);
pLabelScore->setPosition(Vec2(50.f, 22.f));
pLabelScore->setColor(Color3B::ORANGE);
pLabelScore->setFontName("123");
pLabelScore->ignoreContentAdaptWithSize(false);
pLabelScore->setContentSize(Size(128.f, 60.f));
pLabelScore->setTextAreaSize(Size(128.f, 100.f));
pLabelScore->setTextVerticalAlignment(TextVAlignment::CENTER);
pLabelScore->setTextHorizontalAlignment(TextHAlignment::CENTER);
((Label*)pLabelScore->getVirtualRenderer())->enableOutline(Color4B(0x42, 0x00, 0x00, 0xff), 2);
this->addChild(pLabelScore);


/************************************************************************/
/*       TextAtlas                              */
/************************************************************************/
TextAtlas* pLockLevel = TextAtlas::create(StringUtils::format("%d", 50), "OtherImage.bundle/Num/NetTab_Num.png", 28, 40, "0");
pLockLevel->setScale(0.7f);
pLockLevel->setAnchorPoint(Vec2(0.f, 0.5f));
pLockLevel->setPosition(Vec2(480.f, 320.f));
this->addChild(pLockLevel);


/************************************************************************/
/*       TableView                       */
/************************************************************************/
auto _tableView = TableView::create(this, Size(730.f, 360.f));
_tableView->setColor(Color3B::RED);
_tableView->setDirection(cocos2d::extension::ScrollView::Direction::VERTICAL);
_tableView->setAnchorPoint(Point::ZERO);
_tableView->setPosition(Vec2(114.f, 142.f));
_tableView->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN);//列表设置为从小到大显示,及idx从0开始  如果是TableView::VerticalFillOrder::BOTTOM_UP列表设置为从大到小显示,及idx从idx-1开始;
_tableView->setDelegate(this);
//_tableView->setClippingToBounds(true);
this->addChild(_tableView);
_tableView->reloadData();//重新加载数据从数据源。该视图将刷新。;


/************************************************************************/
/*       ListView                       */
/************************************************************************/
auto m_pListView = ListView::create();
m_pListView->setBackGroundImage("green_edit.png");
m_pListView->setBackGroundImageScale9Enabled(true);
m_pListView->setContentSize(Size(500.f, 410.f));
m_pListView->setPosition(Vec2(22.f, 25.f));
m_pListView->setDirection(ListView::Direction::VERTICAL);
m_pListView->setGravity(ListView::Gravity::CENTER_VERTICAL);
m_pListView->setItemsMargin(160.f);
m_pListView->setItemModel(Layout::create());
m_pListView->pushBackDefaultItem();
//m_pListView->sortAllChildren();
//m_pListView->setScrollBarEnabled(false);
this->addChild(m_pListView);
//假设有17个头像,每行五个;
int size = 15;
for (int i = 0; i < ceil(size / 5.f); ++i)//多少行;
{
Layout* custom_item = Layout::create();//一行层模块;
custom_item->setContentSize(Size(640.f, 180.f));
for (unsigned u = 0; u < 5; u++)//多少列;
{
if (u + i * 5 >= size)//数量相等退出循环;
break;
//道具名称;
Text* pLabelName = Text::create("132", "", 17);
pLabelName->setPosition(Vec2(50.f, 70.f));
custom_item->addChild(pLabelName);
pLabelName->setTag(21113);
}
m_pListView->pushBackCustomItem(custom_item);
}
// 添加事件监听器(ListView)
m_pListView->addEventListener((ui::ListView::ccListViewCallback)[=](Ref *pSender, ListView::EventType type){
switch (type)
{
case ListView::EventType::ON_SELECTED_ITEM_START:
{
ListView* listView = static_cast(pSender);
log("select child start index = %ld", listView->getCurSelectedIndex());
break;
}
case ListView::EventType::ON_SELECTED_ITEM_END:
{
ListView* listView = static_cast(pSender);
log("select child end index = %ld", listView->getCurSelectedIndex());
break;
}
default:
break;
}
});


// 添加事件监听器(ScrollView);
m_pListView->addEventListener((ui::ScrollView::ccScrollViewCallback)[=](Ref* pSender, ui::ScrollView::EventType type){
switch (type) {
case  ui::ScrollView::EventType::SCROLL_TO_BOTTOM:
log("SCROLL_TO_BOTTOM");
break;
case  ui::ScrollView::EventType::SCROLL_TO_TOP:
log("SCROLL_TO_TOP");
break;
default:
break;
}
});
/************************************************************************/
/*       ScrollView                       */
/************************************************************************/
//创建滚动层的大小;
Size backgroundSize = Size(960, 200);
//创建一个ScrollView滚动层容器;
auto m_ScrollView = ui::ScrollView::create();
//激活反弹,拉过了之后,可以弹回来;
m_ScrollView->setBounceEnabled(true);
m_ScrollView->setScrollBarEnabled(false);
m_ScrollView->setTag(101);
//设置滚动方向垂直滚动;
m_ScrollView->setDirection(ui::ScrollView::Direction::HORIZONTAL);
//设置滚动层的大小;
m_ScrollView->setContentSize(Size(backgroundSize.width, backgroundSize.height));//外部窗口大小;
m_ScrollView->setPosition(Vec2(0, 140));//为滚动层左下角的坐标;
float innerHeight = m_ScrollView->getContentSize().height;
float innerWidth = 0.f;
m_ScrollView->setInnerContainerSize(Size(innerWidth, innerHeight));
this->addChild(m_ScrollView, 10);


m_ScrollView->addEventListener(ui::ScrollView::ccScrollViewCallback(CC_CALLBACK_2(HelloWorld::onScrowViewMove, this)));
m_ScrollView->setScrollBarEnabled(false);
float x = m_ScrollView->getInnerContainer()->getPosition().x;//getPositionX()
float width = m_ScrollView->getInnerContainerSize().width;
m_ScrollView->scrollToPercentHorizontal(30, 0.2f, true);
m_ScrollView->setInnerContainerSize(Size(435.f, 340.f));
m_ScrollView->jumpToPercentHorizontal(100.f);
m_ScrollView->jumpToBottomLeft();




/************************************************************************/
/*       PageView                       */
/************************************************************************/
auto m_pageView = ui::PageView::create();
//m_pageView->addEventListener((const ui::ScrollView::ccScrollViewCallback&)CC_CALLBACK_2(HelloWorld::TurningCallBack, this));

m_pageView->setContentSize(Size(940.f, 520.f));
m_pageView->setPosition(Vec2(10.f, 10.f));
m_pageView->addEventListener((PageView::ccPageViewCallback)[=](Ref* ref, ui::PageView::EventType type){
if (type == PageView::EventType::TURNING)
{
PageView* pageView = dynamic_cast(ref);
// 在_displayValueLabel文本中显示PageIndex
Label* lb;
lb->setString(StringUtils::format("page = %ld", pageView->getCurPageIndex() + 1));
}
});//等价于m_pageView->addEventListener((PageView::ccPageViewCallback)CC_CALLBACK_2(HelloWorld::TurningCallBack, this));里面的内容为上面的内容;
//创建三个layout(关卡图片)//设置页数;
for (int i = 1; i <= 3; i++)//有三页;
{
//创建一个layout;
Layout *lo = Layout::create();
lo->setBackGroundImage("");
lo->setBackGroundImageScale9Enabled(true);
lo->setContentSize(Size(960, 480));
for (int j = 1; j <= 3; j++)
{
//底图;
auto imageView = ImageView::create(StringUtils::format("fang%d.png", j));
imageView->setPosition(Vec2(j * 300 - 125, m_pageView->getContentSize().height / 2));
lo->addChild(imageView);


//Button
auto btn = Button::create("[email protected]");
btn->setTag(j);
btn->setPosition(Vec2(imageView->getContentSize().width / 2, 20));
btn->addTouchEventListener([=](Ref* pSender, Widget::TouchEventType type){
if (type == Widget::TouchEventType::ENDED)
{
if (btn->getTag() == 1)
{
log("first_btn1");
}
if (btn->getTag() == 2)
{
log("first_btn2");
}
if (btn->getTag() == 3)
{
log("first_btn3");
}
}
});
imageView->addChild(btn);
}
m_pageView->addPage(lo);
}
this->addChild(m_pageView);
/************************************************************************/
/*       RichText                       */
/************************************************************************/
auto richText = RichText::create();
richText->ignoreContentAdaptWithSize(true);
RichElementText* textLabel = RichElementText::create(0, Color3B::WHITE, 255, "123.png", "Arial", 18);
richText->pushBackElement(textLabel);
RichElementText* textNum = RichElementText::create(0, Color3B(0xff, 0xe7, 0x37), 255, "123.png", "Arial", 18);
richText->pushBackElement(textNum);
richText->setAnchorPoint(Vec2(0.f, 1.f));
this->addChild(richText, 5);
richText->setPosition(Vec2(8.0f, 27.f));
richText->removeAllChildren();


/************************************************************************/
/*       EditBox                       */
/************************************************************************/


auto _pInputChat = ui::EditBox::create(Size(412.f, 55.f), ui::Scale9Sprite::createWithSpriteFrameName("p_gemcoin_bg.png"));
_pInputChat->setAnchorPoint(Vec2(0.f, 0.5f));
_pInputChat->setPosition(Vec2(15.f, 33.f));
_pInputChat->setReturnType(ui::EditBox::KeyboardReturnType::DONE);
_pInputChat->setInputMode(ui::EditBox::InputMode::SINGLE_LINE);
_pInputChat->setDelegate(this);
_pInputChat->setOpacity(0);
_pInputChat->setFont("123", 18);
_pInputChat->setFontColor(Color4B(0x73, 0x7a, 0x9e, 0xff));
_pInputChat->setPlaceHolder("ffdf");
_pInputChat->setPlaceholderFont("123", 22);
_pInputChat->setPlaceholderFontName("132");
_pInputChat->setPlaceholderFontColor(Color4B(0x73, 0x7a, 0x9e, 0xff));
_pInputChat->setMaxLength(100);
_pInputChat->setReturnType(ui::EditBox::KeyboardReturnType::DONE);


this->addChild(_pInputChat, 3);




/************************************************************************/
/*       CheckBox                       */
/************************************************************************/
auto pCheckBt = ui::CheckBox::create("AttributeCues_btn_EnableBg.png", "AttributeCues_btn_EnableBg.png", "Right_Icon.png",
"Right_Icon.png", "AttributeCues_btn_EnableBg.png", ui::Widget::TextureResType::PLIST);
pCheckBt->addEventListener(CC_CALLBACK_2(HelloWorld::CheckBoxCallBack, this));
pCheckBt->setTag(1);
pCheckBt->setPosition(Vec2(237, 230));
addChild(pCheckBt);


/************************************************************************/
/*       LoadingBar                       */
/************************************************************************/
// 创建一个LoadingBar;
auto loadingBar = LoadingBar::create("loadingbar.png");
// 设置进度条从左向右递增;
loadingBar->setDirection(LoadingBar::Direction::LEFT);
// 设置tag值,之后在update函数中可以通过getChildByTag函数获取这个LoadingBar对象;
loadingBar->setTag(100);
// 设置坐标位置;
loadingBar->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
// 将LoadingBar添加为当前层的子节点;
this->addChild(loadingBar);
// 启用定时器回调更新函数;
this->scheduleUpdate();




/************************************************************************/
/*       Slider                       */
/************************************************************************/
// 创建一个滑动条;
auto slider = Slider::create();
// 设置滑动条的纹理;
slider->loadBarTexture("sliderTrack.png");
// 设置滑动条的滚轮纹理;
slider->loadSlidBallTextures("sliderThumb.png", "sliderThumb.png", "");
// 设置处理滑动条的进度条纹理;
slider->loadProgressBarTexture("sliderProgress.png");
slider->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
// 添加事件监听器;
slider->addEventListener([=](Ref* pSender, Slider::EventType type){
// 当滑块的百分比发生变化时;
if (type == Slider::EventType::ON_PERCENTAGE_CHANGED)
{
// 获得滑动条百分比;
std::string value = StringUtils::format("Percent = %d", slider->getPercent());
// 设置到TextLabel当中显示;
label->setString(value);
}
});
this->addChild(slider);




/************************************************************************/
/*       TextField                       */
/************************************************************************/
// 创建文本框;
auto textField = TextField::create("请输入数据", "Arial", 48);
textField->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 + 50));
// 添加文本框事件监听器;
textField->addEventListener([=](Ref *pSender, TextField::EventType type){
// 根据文本框的事件类型执行相应的代码;
switch (type)
{
case TextField::EventType::ATTACH_WITH_IME:
label->setString("输入开始");
break;
case TextField::EventType::DETACH_WITH_IME:
{
label->setString("输入完成");
// 获得文本框输入的数据;
std::string value = textField->getStringValue();
// 如果数据大于0,显示在_messageValueLabel当中
if (value.length() > 0)
{
label->setString("你输入的数据:" + value);
}
else
{
label->setString("你没有输入数据");
}
}
break;
case TextField::EventType::INSERT_TEXT:
label->setString("插入数据");
break;
case TextField::EventType::DELETE_BACKWARD:
label->setString("删除数据");
break;
default:
break;
}


});
this->addChild(textField);






/************************************************************************/
/*       scheduleUpdate                       */
/************************************************************************/
scheduleUpdate();


/************************************************************************/
/*       schedule                       */
/************************************************************************/
schedule(schedule_selector(HelloWorld::timeup), 1.0f);


/************************************************************************/
/*       scheduleOnce                       */
/************************************************************************/
scheduleOnce(schedule_selector(HelloWorld::timeup), 8.f);


/************************************************************************/
/*       ParticleSystemQuad                       */
/************************************************************************/
ParticleSystem*  _pScoreTail = ParticleSystemQuad::create("OtherImage.bundle/Particle/DeskScore.plist");
_pScoreTail->setPositionType(ParticleSystem::PositionType::RELATIVE);
_pScoreTail->setAutoRemoveOnFinish(true);
_pScoreTail->setVisible(false);
addChild(_pScoreTail, 60);
_pScoreTail->stopSystem();
_pScoreTail->resetSystem();




/************************************************************************/
/*       Animation                       */
/************************************************************************/
//第一种;
Vector effectList;
for (int32_t i = 0; i < 18; i++)
{
auto pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(StringUtils::format("cp_heart_break (%d).png", i + 1));
effectList.pushBack(pFrame);
}


auto m_pFrameHeartEffect = Sprite::createWithSpriteFrameName("cp_heart_break (1).png");
m_pFrameHeartEffect->setScale(1.6f);
m_pFrameHeartEffect->setPosition(480.f,320.f);
m_pFrameHeartEffect->setVisible(false);
m_pFrameHeartEffect->runAction(Sequence::create(
DelayTime::create(0.75f),
CallFuncN::create([&](Node* pNode)
{
pNode->setVisible(true);
}),
Animate::create(Animation::createWithSpriteFrames(effectList, 0.048f)), RemoveSelf::create(), NULL));
this->addChild(m_pFrameHeartEffect);
//第二种;
// ①创建动画对象,它是将动画帧元素的集合对象,决定了动画帧的播放顺序以及时间间隔;
auto animation = Animation::create();
// ②循环使用单张图片来创建动画帧;
for (int i = 46; i < 55; i++)
{
// 将单张图片添加为精灵帧(即动画帧);
animation->addSpriteFrameWithFile(StringUtils::format("100%d.png", i));
}
// 设置动画播放的属性,3秒/15帧;
animation->setDelayPerUnit(3.0f / 15.0f);
// 让精灵对象在动画执行完后恢复到最初状态;
animation->setRestoreOriginalFrame(true);
// ③创建动画动作;
auto animate = Animate::create(animation);
// ④精灵对象(英雄)执行动画动作;
m_pFrameHeartEffect->runAction(animate);


//第三种;
// ①获取精灵帧缓存的单例对象,并读取grossini.plist文件将精灵帧纹理添加到精灵帧缓存当中;
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("grossini.plist");
// 创建精灵对象(舞蹈者);
auto dance = Sprite::create("grossini_dance_01.png");
// 设置精灵对象(舞蹈者)位置为屏幕正中;
dance->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
// 把精灵对象(舞蹈者)添加为HelloWorldLayer层的子节点。;
this->addChild(dance);
// ②创建动画帧缓冲并向缓冲区中添加动画文件;
AnimationCache::getInstance()->addAnimationsWithFile("animations.plist");
// ③从缓冲区中获取文件中设定的名称为“dance_1”的动画对象。;
auto animation = AnimationCache::getInstance()->getAnimation("dance_1");
// ④根据动画对象创建动画动作;
auto animate = Animate::create(animation);
// 精灵对象(舞蹈者)执行动画动作;
dance->runAction(animate);




//第四种;
// ①获取精灵帧缓存的单例对象,并读取animation.plist文件将精灵帧纹理添加到精灵帧缓存当中;
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("animation.plist");
// ②使用精灵帧缓存中的精灵创建一个动画,并设置属性;
auto animation = Animation::create();
// 循环从精灵帧缓存中获取与图片名称相对应的精灵帧组成动画;
for (int i = 1; i <= 8; i++){
std::string szName = StringUtils::format("z_00_0%d.png", i);
// 将单张图片添加为精灵帧(即动画帧)      animation->addSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName(szName));
}
// 设置动画播放的属性,3秒/15帧
animation->setDelayPerUnit(3.0f / 15.0f);
// 让精灵对象在动画执行完后恢复到最初状态;
animation->setRestoreOriginalFrame(true);
// ③用动画帧缓冲AnimationCache缓存所有动画和动画帧;
AnimationCache::getInstance()->addAnimation(animation, "walk");


// ④创建背景精灵添加到当前层;
auto bgSprite = Sprite::createWithSpriteFrameName("gamebg.png");
bgSprite->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
this->addChild(bgSprite);
// ⑤创建僵尸精灵,设置坐标位置在屏幕之外,并添加到当前层;
auto zSprite = Sprite::createWithSpriteFrameName("z_00_01.png");    zSprite->setPosition(Vec2(visibleSize.width + zSprite->getContentSize().width / 2, visibleSize.height / 2));
this->addChild(zSprite);
// ⑥从动画帧缓冲AnimationCache中获取之前缓存的动画;
auto walk = AnimationCache::getInstance()->getAnimation("walk");
// ⑦创建动画动作;
auto animate = Animate::create(walk);
// 创建一个重复动作,重复执行Animate动画动作;
auto repeatanimate = RepeatForever::create(animate);
// 定义一个移动动作,让精灵对象从屏幕右边移动到屏幕左边;
auto moveTo = MoveTo::create(10.f, Vec2(-zSprite->getContentSize().width / 2, visibleSize.height / 2));
// ⑧僵尸精灵执行重复动作(包含动画动作)和移动动作,执行效果是僵尸从屏幕的右边走到屏幕的左边;
zSprite->runAction(repeatanimate);
zSprite->runAction(moveTo);


/************************************************************************/
/*       XML动画                       */
/************************************************************************/
ArmatureDataManager::getInstance()->addArmatureFileInfo(".png",".plist",".xml");
Armature* pArmature = Armature::create("AnimationGilr");
pArmature->getAnimation()->setSpeedScale(0.33f);
pArmature->getAnimation()->playWithIndex(0);
pArmature->setPosition(Vec2(0,0));
this->addChild(pArmature);


/************************************************************************/
/*       EventListenerTouchOneByOne           */
/************************************************************************/
// 注册touch监听;
// ①创建一个单点触摸事件监听器,处理触摸事件逻辑;
auto Listener = EventListenerTouchOneByOne::create();
Listener->setSwallowTouches(true);
Listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
Listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
Listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
Listener->onTouchCancelled = CC_CALLBACK_2(HelloWorld::onTouchCancelled, this);
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(Listener, this);


//Listener->onTouchBegan = [=](Touch* touch, Event* event){return true;};
//Listener->onTouchMoved = [=](Touch* touch, Event* event){};
//Listener->onTouchEnded = [=](Touch* touch, Event* event){};
//Listener->onTouchCancelled = [=](Touch* touch, Event* event){};


/************************************************************************/
/*       EventListenerKeyboard                       */
/************************************************************************/
auto keyboardlistener = EventListenerKeyboard::create();
keyboardlistener->onKeyReleased = CC_CALLBACK_2(HelloWorld::onKeyReleased, this);
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboardlistener, this);


/************************************************************************/
/*       CocosStudio                       */
/************************************************************************/
ui::Widget* addUi = dynamic_cast(cocostudio::GUIReader::getInstance()->widgetFromJsonFile("PublicBackground.ExportJson"));
//Layout* addUi = (Layout*)dynamic_cast(cocostudio::GUIReader::getInstance()->widgetFromJsonFile("PublicBackground.ExportJson"));
addUi->setPosition(Point::ZERO);
addUi->setTouchEnabled(false);
addChild(addUi);
//若addUI为Layout类型时可以设置背景addUi->setBackGroundImage("123.png", ui::Widget::TextureResType::LOCAL);
//注意:若是某个控件在某个父控件下,也可以通过父控件得到子控件名称获取到子控件 如;
Layout* pLayoutScene = (Layout*)addUi->getChildByName("Panel_scene");
auto m_pImgSceneBk = (ImageView*)pLayoutScene->getChildByName("Image_sceneBk");


//图片;
auto imageView = static_cast(ui::Helper::seekWidgetByName(addUi, "BackGround_ImageView_Bg"));
//文字;
auto label = static_cast(ui::Helper::seekWidgetByName(addUi, "Background_Label_Title"));
//返回按钮;
auto pBackBtn = static_cast(ui::Helper::seekWidgetByName(addUi, "Background_Button_Return"));
//数字标签;
auto pSelfNum = static_cast(ui::Helper::seekWidgetByName(addUi, "CycRankUp_AtlasLabel_SelfRankNum"));
//滚动条;
auto m_pScrollViewLevel = (ui::ScrollView*)Helper::seekWidgetByName(addUi, "ScrollView_ach");
//ListView
auto m_pListView = (ListView*)Helper::seekWidgetByName(addUi, "ListView_props");
//进度条LoadingBar;
auto progressNode = dynamic_cast(ui::Helper::seekWidgetByName(addUi, "ProgressBar"));
//九宫格图片;
auto viewBg = (ui::Scale9Sprite*)(ui::Helper::seekWidgetByName(addUi, "Image_viewBg"));
//布局(层容器);
auto thepanel = dynamic_cast(ui::Helper::seekWidgetByName(addUi, "Panel_part1"));


    return true;
}




void HelloWorld::menuCloseCallback(Ref* pSender)
{


    Director::getInstance()->end();
    #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
     
}


void HelloWorld::menuCallBack(Ref* pSender)
{


}


void HelloWorld::onKeyReleased(EventKeyboard::KeyCode code, Event* event)
{
if (code == EventKeyboard::KeyCode::KEY_ESCAPE)
{
log("KEY_ESCAPE");
}
}


void HelloWorld::timeup(float t)
{
if (_time <= 0)
{
unschedule(schedule_selector(HelloWorld::timeup));
}
_time--;
}


Size HelloWorld::cellSizeForTable(TableView *table)
{
return Size(520, 20);
}


Size HelloWorld::tableCellSizeForIndex(TableView *table, ssize_t idx)
{
return Size(520, 20);
}
cocos2d::extension::TableViewCell* HelloWorld::tableCellAtIndex(TableView *table, ssize_t idx)
{
TableViewCell* pCell = table->dequeueCell();
if (!pCell)
{
pCell = TableViewCell::create();


}
else
{
pCell->removeAllChildren();
}
return pCell;
}




ssize_t HelloWorld::numberOfCellsInTableView(TableView *table)
{
return 1;
}


void HelloWorld::buttonCallBack(Ref* sender, Widget::TouchEventType type)
{
log("addTouchEventListener");
Button* button = (Button*)sender;
if (type == Widget::TouchEventType::ENDED)
{
int tag = button->getTag();
switch (tag)
{
case 0:
break;
case 1:
break;
default:
break;
}
}
}


void HelloWorld::bttCallBack(Ref* sender)
{
log("addClickEventListener");
}


void HelloWorld::onScrowViewMove(Ref* sender, ui::ScrollView::EventType type)
{
if (type == ui::ScrollView::EventType::AUTOSCROLL_ENDED)
{
log("ScrollView");
}
}


void HelloWorld::onImageViewCallback(Ref* sender, Widget::TouchEventType type)
{
if (type == Widget::TouchEventType::ENDED)
{
ImageView* pBtnImg = (ImageView*)sender;
int nTag = pBtnImg->getTag();
}
}


void HelloWorld::update(float delta)
{

// 自增
_time++;
// 当_count变量的值大于100,归零
if (_time > 100) {
_time = 0;
}
// 通过tag值获得LoadingBar对象
auto loadingBar = static_cast(this->getChildByTag(100));
// 修改LoadingBar对象的进度
loadingBar->setPercent(_time);
// 在文本中显示LoadingBar对象当前的进度
label->setString(StringUtils::format("Percent = %0.0f", loadingBar->getPercent()));


}


bool HelloWorld::onTouchBegan(Touch *touch, Event *unused_event)
{
// 获得当前事件触摸的目标对象;
auto target = static_cast(unused_event->getCurrentTarget());
// 获得当前的触摸点;
Point locationInNode = target->convertToNodeSpace(touch->getLocation());
// 获得触摸对象的ContentSize
Size s = target->getContentSize();
// 获得位置矩形;
Rect rect = Rect(0, 0, s.width, s.height);
// 如果位置矩形包含触摸点;
if (rect.containsPoint(locationInNode))
{
log("onTouchBegan... x = %f, y = %f", locationInNode.x, locationInNode.y);
// 设置透明度;
target->setOpacity(180);
// 表明用户触摸事件已经被处理,后续的onTouchMoved、onTouchEnded和onTouchCancelled会接着响应,其他事件监听器则不会再去进行监听本次触摸事件。
return true;
}
return false;
}


void HelloWorld::onTouchMoved(Touch* touch, Event *unused_event)
{
auto target = static_cast(unused_event->getCurrentTarget());
// 移动触摸的精灵;
target->setPosition(target->getPosition() + touch->getDelta());
}


void HelloWorld::onTouchEnded(Touch* touch, Event *unused_event)
{
auto target = static_cast(unused_event->getCurrentTarget());
// 设置透明度;
target->setOpacity(255);
std::string name;
Sprite* sprite;
Label* label;
if (target == sprite)
{
name = "MagentaSquare.png";
sprite->setZOrder(100);
label->setString("响应事件的是酒红色滑块,青色滑块的ZOrder值修改为100");
}
else if (target == sprite)
{
name = "CyanSquare.png";
sprite->setZOrder(0);
label->setString("响应事件的是青色滑块,青色滑块的ZOrder值修改为0");
}
else{
name = "YellowSquare.png";
}
log("onTouchEnded.. 您触摸的是%s", name.c_str());
}


void HelloWorld::TurningCallBack(Ref* ref, ui::ScrollView::EventType type)
{
if (ui::ScrollView::EventType::CONTAINER_MOVED == type)
{
int currentIdx = (int)m_pageView->getCurrentPageIndex();


ui::Widget* showedPage = m_pageView->getItem(currentIdx);
int size = m_pageView->getItems().size();
}
}


void HelloWorld::CheckBoxCallBack(Ref* obj, ui::CheckBox::EventType type)
{
auto pCheckBt = (ui::CheckBox*)obj;
bool isCheck = pCheckBt->isSelected();
pCheckBt->setSelected(false);
if (type == ui::CheckBox::EventType::SELECTED)//被选中;
{
log("SELECTED");
}
}







你可能感兴趣的:(Cocos2d-x)