本篇介紹ScrollView的基本用法以及實作自動滾動。
1.在HelloWorldScene.h中
#include "ui/UIScrollView.h"
//在class HelloWorld中添加 row(行數) total(總行數)
private:
float row = ;
float total = ;
cocos2d::ui::ScrollView* sv ;
2.在HelloWorldScene.cpp中
#include "ui/UIImageView.h"
//建立一個imageView當做模闆
ImageView* img = ImageView::create("res/frame_Description_b.png");
Size _size = img->getContentSize();
//開啟九宮格
img->setScale9Enabled(true);
img->setCapInsets(Rect(, , _size.width-, _size.height-));
img->setContentSize(Size(, ));
img->setAnchorPoint(Vec2(,));
//計算ScrollView内部布局的高度
float h = + img->getContentSize().height * total ;
sv = ScrollView::create();
//setContentSize設定的是ScrollView的可視尺寸
sv->setContentSize(Size(, ));
//setInnerContainerSize設定的是ScrollView内部布局的尺寸
sv->setInnerContainerSize(Size(, h));
sv->setDirection(ui::ScrollView::Direction::VERTICAL);
sv->setBounceEnabled(true);
addChild(sv);
sv->setPosition(Vec2(visibleSize.width/ + origin.x, visibleSize.height/ + origin.y));
//添加ScrollView的子節點
for (int i=; i<; i++) {
auto c_img = img->clone();
sv->addChild(c_img);
float x = * (i%+) + img->getContentSize().width * (i%) ;
float y = h - (i/) * img->getContentSize().height - * (i/+) ;
c_img->setPosition(Vec2(x, y));
}
//自動滾動 實作效果是每一次0.5秒後ScrollView的内部布局容器用0.1秒速度無衰減滾動20% 共5次
Sequence* se = Sequence::create(DelayTime::create(), CallFunc::create([this]{
sv->scrollToPercentVertical(row / total * 100, 0.1, false);
row++;
}), NULL);
sv->runAction(Repeat::create(se, total));
自動滾動依賴于
void scrollToPercentVertical(float percent,float timeInSec,bool attenuated)
參數
percent 百分比,從0至100
second 動作執行時間
attenuated 滾動速度是否發生衰減
類似方法還有
void scrollToPercentHorizontal(float percent,float timeInSec,bool attenuated)
在豎直方向和水準方向分别按一定的百分比滾動内部布局容器
void scrollToPercentBothDirection(const Vec2& percent,float timeInSec,bool attenuated)
參數
percent 百分比,x分量代表水準百分比,y分量代表豎直百分比
second 動作所需時間
attenuated 滾動速度是否發生衰減