ScrollView的使用以及自动滚动

本篇介绍ScrollView的基本用法以及实现自动滚动。

1.在HelloWorldScene.h中

#include "ui/UIScrollView.h"

//在class HelloWorld中添加 row(行数) total(总行数)
private:
    float row = 1.0f ;
    float total = 5.0f ;
    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(20, 20, _size.width-40, _size.height-40));
img->setContentSize(Size(200, 170));
img->setAnchorPoint(Vec2(0,1));

//计算ScrollView内部布局的高度
float h = 60 + img->getContentSize().height * total ;
sv = ScrollView::create();
//setContentSize设置的是ScrollView的可视尺寸
sv->setContentSize(Size(430, 240));
//setInnerContainerSize设置的是ScrollView内部布局的尺寸
sv->setInnerContainerSize(Size(430, h));
sv->setDirection(ui::ScrollView::Direction::VERTICAL);
sv->setBounceEnabled(true);
addChild(sv);
sv->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

//添加ScrollView的子节点
 for (int i=0; i<10; i++) {
     auto c_img = img->clone();
     sv->addChild(c_img);
     float x = 10 * (i%2+1) + img->getContentSize().width * (i%2) ;
     float y = h - (i/2) * img->getContentSize().height - 10 * (i/2+1) ;
     c_img->setPosition(Vec2(x, y));
}

//自动滚动 实现效果是每一次0.5秒后ScrollView的内部布局容器用0.1秒速度无衰减滚动20% 共5次
Sequence* se = Sequence::create(DelayTime::create(0.5), 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 滚动速度是否发生衰减

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值