首先引入包含control控件所需声明的头文件和命名空间,#include "extensions/cocos-ext.h" using namespace extension;
自定义类,公有继承自 Layer 、ScrollViewDelegate,见以下代码:
OtherGUILayer.hpp
#ifdef OtherGUILayer_hpp
#define OtherGUILayer_hpp
#include "cocos2d.h"
USING_NS_CC;
#include "extensions/cocos-ext.h"
using namespace extension;
class OtherGUILayer: public Layer,public ScrollViewDelegate{
public:
static Scene* createScene();
virtual bool init()override;
CREATE_FUNC(OtherGUILayer);
public:
virtual void scrollViewDidScroll(extension::ScrollView* view);
virtual void scrollViewDidZoom(extension::ScrollView* view);
public:
//测试ScrollView
void addScrollView();
};
#endif
OtherGUILayer.cpp
#include "OtherGUILayer.hpp"
#define WINSIZE Director::getInstance()->getWinSize()
Scene* OtherGUILayer::createScene(){
auto scene = Scene::create();
auto layer = OtherGUILayer::create();
scene->addChild(layer);
return scene;
}
bool OtherGUILayer::init(){
if(!Layer::init()){
return false;
}
auto bg = LayerColor::create(Color4B::YELLOW);
this->addChild(bg);
this->addScrollView();
return true;
}
void OtherGUILayer::addScrollView(){
auto sp = Sprite::create("HelloWorld.png");
//获取原图片的大小
auto size = sp->getContentSize();
//获取图片实际大小
//auto size1 = sp->getBoundingBox();
auto container = Layer::create();
container->setContentSize(Size(size.width*10,size.height));
for(int i = 0;i<10;i++){
auto label = Label::create();
label->setString(StringUtils::format("%d",i));
label->setSystemFontSize(80);
label->setColor(Color3B::RED);
label->setPosition(Vec2(size.width/2*(i+1),size.height/2));
container->addChild(label);
}
//参数 大小 可视区域内容
auto scrollView = ScrollView::create(size,container);
scrollView->setPosition(WINSIZE/2.0f);
this->addChild(scrollView);
//设置滑动方向
scrollView->setDirection(ScrollView::Direction::HORIZONTAL);
//是否开启弹性效果
scrollView->setBounceable(true);
//设置代理
scrollView->setDelegate(this);
}
void OtherGUILayer::scrollViewDidScroll(ScrollView* view){
//获取偏移
auto offset = view->getContentOffset();
CCLOG("offset x = %f,y = %f",offset.x,offset.y);
}
void OtherGUILayer::scrollViewDidZoom(ScrollView* view){
//获取缩放
auto scale = view->getZoomScale();
CCLOG("scale:%f",scale);
}