调试了一下午发现CCScrollView的一些注意小细节
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC;
USING_NS_CC_EXT;
class HelloWorld : public CCLayer//CCScrollView
{
public:
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::CCScene* scene();
// a selector callback
void menuCloseCallback(CCObject* pSender);
// implement the "static node()" method manually
CREATE_FUNC(HelloWorld);
CCLayer* getTheContainer();
private:
CC_SYNTHESIZE_RETAIN(CCScrollView* , m_ScrollView, ScrollView);
};
#endif // __HELLOWORLD_SCENE_H__
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
m_ScrollView = CCScrollView::create();
getScrollView()->setContentSize(CCSizeMake(visibleSize.width * 5, visibleSize.height)); // 1
//getScrollView()->setContentSize(CCSizeMake(visibleSize.width, visibleSize.height)); //2
getScrollView()->setViewSize(visibleSize);
getScrollView()->setContainer(getTheContainer());
getScrollView()->setDirection(kCCScrollViewDirectionHorizontal);
addChild(getScrollView());
return true;
}
CCLayer* HelloWorld::getTheContainer() {
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCLayer* pNode = CCLayer::create();
CCPoint centerPoint = ccp(visibleSize.width / 2, visibleSize.height / 2);
for (int i = 0; i < 5; ++i) {
CCSprite* pSprite = CCSprite::create("HelloWorld.png");
pSprite->setPosition(ccpAdd(centerPoint, ccp(i * visibleSize.width, 0)));
pNode->addChild(pSprite, 0, 0);
}
//pNode->setContentSize(CCSizeMake(visibleSize.width * 5, visibleSize.height)); //3
pNode->setContentSize(CCSizeMake(visibleSize.width, visibleSize.height)); //4
return pNode;
}
创建一个容器层,存放你要滚动的内容,然后我这里用的是5个精灵,也就是屏幕的5倍宽,之前我并没有3、4这段代码,所以滚动后总会跳到第一张图片,因为没有理解
pNode->setContentSize的含义,我加入了5张图片,那个容器层的大小必须是5倍屏幕宽,而默认的是一倍屏幕宽,所以会导致那个问题。分别运行注释1、2的代码会发现滚动视图的setContentSize决定可以滚动的区域大小,如果是2的话,仅仅是图片移动,而没有滚动。
容器大小(内容尺寸)和 显示(可视)范围
举个例子,好比你透过窗户去看风景,你一眼能看到多少取决于窗户有多大,这里窗户的大小就是可视范围。假设你和窗户是不能移动的,如果你想看到其他不在可视范围内的部分,就需要CCScrollView 来帮你移动风景,容器的大小就是风景的大小,也就是风景的尺寸。
再比如有一张1000*1000像素的图片,设定100*100的可视范围,你每次只能看到百分之一的范围,但是通过移动图片的位置,你能看全整张图片。1000*1000就是内容尺寸,100*100就是显示范围。
将一个大的范围遮起来,只露一个小窗口,但是允许你一点一点的滚动,这就是CCScrollView 的工作。