Cocos2d-x 布局Layout , VBox,HBox可以互相嵌套

本文介绍如何使用Cocos2d-x游戏引擎创建复杂的UI布局,包括水平布局(VBox)与垂直布局(HBox)的嵌套使用,并通过代码示例展示了如何设置触摸事件监听及响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



Size winSize = Director::getInstance()->getVisibleSize();
 Layout* _verticalLayout = cocos2d::ui::VBox::create();//水平布局
 _verticalLayout->setPosition(Vec2(winSize.width / 2 - 80,winSize.height - 70));
 Layer* _uiLayer = Layer::create();
 _uiLayer->addChild(_verticalLayout);
 _verticalLayout->setScale(0.5);

 _verticalLayout->setFocused(true);
 _verticalLayout->setLoopFocus(true);
 _verticalLayout->setTag(100);
 //_firstFocusedWidget = _verticalLayout;

 int count1 = 1;
 for (int i = 0; i<count1; ++i) {
  ImageView *w = ImageView::create("scrollviewbg.png");
  w->setAnchorPoint(Vec2::ZERO);
  w->setTouchEnabled(true);
  w->setScaleX(2.5);
  w->setTag(i + count1);
  w->addTouchEventListener(CC_CALLBACK_2(HelloWorld::onImageViewClicked, this));
  _verticalLayout->addChild(w);
 }

 //add HBox into VBox
 HBox *hbox = HBox::create();//垂直布局
 hbox->setScale(0.8f);
 hbox->setTag(101);
 _verticalLayout->addChild(hbox);

 int count2 = 2;
 for (int i = 0; i < count2; ++i) {
  ImageView *w = ImageView::create("scrollviewbg.png");
  w->setAnchorPoint(Vec2(0, 1));
  w->setScaleY(2.0);
  w->setTouchEnabled(true);
  w->setTag(i + count1 + count2);
  w->addTouchEventListener(CC_CALLBACK_2(HelloWorld::onImageViewClicked, this));
  hbox->addChild(w);
 }

 VBox *innerVBox = VBox::create();
 hbox->addChild(innerVBox);//水平布局中加入垂直布局
 innerVBox->setTag(102);
 //        innerVBox->setPassFocusToChild(false);
 //        innerVBox->setFocusEnabled(false);


 int count3 = 2;
 for (int i = 0; i<count3; ++i) {
  ImageView *w = ImageView::create("scrollviewbg.png");
  w->setTouchEnabled(true);
  w->setTag(i + count1 + count2 + count3);
  w->addTouchEventListener(CC_CALLBACK_2(HelloWorld::onImageViewClicked, this));
  innerVBox->addChild(w);
 }

 this->addChild(_verticalLayout);


    return true;
}

void HelloWorld::onImageViewClicked(cocos2d::Ref *ref, cocos2d::ui::Widget::TouchEventType touchType)
{
 if (touchType == cocos2d::ui::Widget::TouchEventType::ENDED) {
  cocos2d::ui::Widget *w = (cocos2d::ui::Widget*)ref;
  if (w->isFocusEnabled()) {
   w->setFocusEnabled(false);
   w->setColor(Color3B::YELLOW);
  }
  else{
   w->setFocusEnabled(true);
   w->setColor(Color3B::WHITE);
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值