现在的位置: 首页 > 综合 > 正文

cocos2dx CCScrollView 源码分析

2018年04月20日 ⁄ 综合 ⁄ 共 21049字 ⁄ 字号 评论关闭

目录(?)[-]

  1. 继承树结构
  2. 重要的成员
  3. 源码解析
    1. ccTouchBegan
    2. ccTouchMoved
      1. setContentOffset
      2. setZoomScale
    3. ccTouchEnded
      1. deaccelerateScrolling
      2. relocateContainer
      3. setContentOffsetInDuration
    4. 小结

版本源码来自2.x,转载请注明

另我实现了可以循环的版本http://blog.csdn.net/u011225840/article/details/31354703

1.继承树结构

可以看出,CCScrollView本质是CCLayer的一种,具备层的一切属性和方法。关于CCLayer的源码分析,后续会有。

2.重要的成员

 1.  CCScrollViewDelegate* m_pDelegate;
cocos2d-x中,运用了很多delegate这种模式。下面简单的说明下delegate这种模式。(至于delegate与proxy的区别,请先参考下headfirst中的proxy三种情况,然后可以google区别,这里不再赘述。)
XXXDelegate中封装了接口(c++中的实现就是虚函数与必须实现的纯虚函数),类A中存在某些方法,比如说View中的getDataNum,View会根据数据的多少来确定界面的显示方式,但是A与数据并没有直接的关联。于是乎,在View A中的getDataNum会调用A内部的DataDelegate的方法来获取数据的多少。至于这个数据具体是什么,只需要实现一个DataDelegate的具体类即可。这样,View与数据的耦合度就非常低。View只依赖抽象的DataDelegate。
在后续的源码分析中,可以看出delegate的妙处。

3.源码解析

3.1 ccTouchBegan


对于ccTouchBegan中的重要部分,我添加了注释。可以通过代码看出,CCscrollView支持单点和双点触摸。

  1. bool CCScrollView::ccTouchBegan(CCTouch* touch, CCEvent* event)  
  2. {  
  3.     if (!this->isVisible() || !m_bCanTouch)  
  4.     {  
  5.         return false;  
  6.     }  
  7.       
  8.     CCRect frame = getViewRect();  
  9.   
  10.     //dispatcher does not know about clipping. reject touches outside visible bounds.
      
  11.     /* 
  12.     1. ccScrollView只允许至多两个触摸点,多于两个后将不会认为发成了触摸。 
  13.     2. 当CCScrollView处于移动状态时,在此状态下新发生触摸将不会被认为发生。 
  14.     3.注意frame不是当前的尺寸,而是当前ViewSize的frame,也就是触摸点必须在显示的Rect内才会认定为触摸(可以通过setViewSize来设置大小) 
  15.    */  
  16.     if (m_pTouches->count() > 2 ||  
  17.         m_bTouchMoved          ||  
  18.         !frame.containsPoint(m_pContainer->convertToWorldSpace(m_pContainer->convertTouchToNodeSpace(touch))))  
  19.     {  
  20.         m_pTouches->removeAllObjects();  
  21.         return false;  
  22.     }  
  23.   
  24.     if (!m_pTouches->containsObject(touch))  
  25.     {  
  26.         m_pTouches->addObject(touch);  
  27.     }  
  28.     //CCLOG("CCScrollView::ccTouchBegan %d", m_pTouches->count());
      
  29.     /* 
  30.      当触摸点为1的时候,设置单点触摸的属性。尤其是m_bDragging属性表示触摸行为是拖动 
  31.    */  
  32.     if (m_pTouches->count() == 1)  
  33.     { // scrolling   
  34.         m_tTouchPoint     = this->convertTouchToNodeSpace(touch);  
  35.         m_bTouchMoved     = false;  
  36.         m_bDragging     = true//dragging started
      
  37.         m_tScrollDistance = ccp(0.0f, 0.0f);  
  38.         m_fTouchLength    = 0.0f;  
  39.     }  
  40.     /* 
  41.         当触摸点个数为2时,设置双点触摸的属性 
  42.     */  
  43.     else if (m_pTouches->count() == 2)  
  44.     {  
  45.         m_tTouchPoint  = ccpMidpoint(this->convertTouchToNodeSpace((CCTouch*)m_pTouches->objectAtIndex(0)),  
  46.                                    this->convertTouchToNodeSpace((CCTouch*)m_pTouches->objectAtIndex(1)));  
  47.         m_fTouchLength = ccpDistance(m_pContainer->convertTouchToNodeSpace((CCTouch*)m_pTouches->objectAtIndex(0)),  
  48.                                    m_pContainer->convertTouchToNodeSpace((CCTouch*)m_pTouches->objectAtIndex(1)));  
  49.         m_bDragging  = false;  
  50.     }   
  51.     return true;  
  52. }  

3.2 ccTouchMoved

同上,代码里面加了注释

  1. void CCScrollView::ccTouchMoved(CCTouch* touch, CCEvent* event)  
  2. {  
  3.       
  4.     if (!this->isVisible())  
  5.     {  
  6.         return;  
  7.     }  
  8.   
  9.     /* 
  10.         如果此时不允许滚动,则退出。这个可以通过set函数设置。默认为false 
  11.     */  
  12.     if(this->m_bScrollLock)  
  13.     {  
  14.         return;  
  15.     }  
  16.   
  17.     if (m_pTouches->containsObject(touch))  
  18.     {  
  19.         /* 
  20.             啊哦,好玩的来咯。 
  21.             滚动状态时 
  22.         */  
  23.         if (m_pTouches->count() == 1 && m_bDragging)  
  24.         { // scrolling   
  25.             CCPoint moveDistance, newPoint, maxInset, minInset;  
  26.             CCRect  frame;  
  27.             float newX, newY;  
  28.               
  29.             frame = getViewRect();  
  30.             //获得当前点的坐标,并且获得当前点与上一次触碰点的距离(moveDistance也是CCPoint,x与y是当前点与上一点的x距离,y距离)
      
  31.             newPoint     = this->convertTouchToNodeSpace((CCTouch*)m_pTouches->objectAtIndex(0));  
  32.             moveDistance = ccpSub(newPoint, m_tTouchPoint);  
  33.               
  34.             float dis = 0.0f;  
  35.             //如果有方向的限定,根据方向限定获取对应的距离
      
  36.             if (m_eDirection == kCCScrollViewDirectionVertical)  
  37.             {  
  38.                 dis = moveDistance.y;  
  39.             }  
  40.             else if (m_eDirection == kCCScrollViewDirectionHorizontal)  
  41.             {  
  42.                 dis = moveDistance.x;  
  43.             }  
  44.             else  
  45.             {  
  46.                 dis = sqrtf(moveDistance.x*moveDistance.x + moveDistance.y*moveDistance.y);  
  47.             }  
  48.   
  49.             //如果移动距离过短,则不判断发生了移动
      
  50.             if (!m_bTouchMoved && fabs(convertDistanceFromPointToInch(dis)) < MOVE_INCH )  
  51.             {  
  52.                 //CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y);
      
  53.                 return;  
  54.             }  
  55.             //第一次移动,则将moveDistance置0
      
  56.             if (!m_bTouchMoved)  
  57.             {  
  58.                 moveDistance = CCPointZero;  
  59.             }  
  60.               
  61.             m_tTouchPoint = newPoint;  
  62.             m_bTouchMoved = true;  
  63.             //点必须在viewRect内部
      
  64.             if (frame.containsPoint(this->convertToWorldSpace(newPoint)))  
  65.             {  
  66.                 //根据可以移动的direction来设置moveDistance
      
  67.                 switch (m_eDirection)  
  68.                 {  
  69.                     case kCCScrollViewDirectionVertical:  
  70.                         moveDistance = ccp(0.0f, moveDistance.y);  
  71.                         break;  
  72.                     case kCCScrollViewDirectionHorizontal:  
  73.                         moveDistance = ccp(moveDistance.x, 0.0f);  
  74.                         break;  
  75.                     default:  
  76.                         break;  
  77.                 }  
  78.                 //这个版本无用啊。。。。   
  79.                 maxInset = m_fMaxInset;  
  80.                 minInset = m_fMinInset;  
  81.   
  82.                 //获取容器的新坐标,注意是容器哦   
  83.                 newX     = m_pContainer->getPosition().x + moveDistance.x;  
  84.                 newY     = m_pContainer->getPosition().y + moveDistance.y;  
  85.                 //滚动的CCPoint矢量设置
      
  86.                 m_tScrollDistance = moveDistance;  
  87.                 this->setContentOffset(ccp(newX, newY));  
  88.             }  
  89.         }  
  90.         //双点触摸时,效果是缩放,len是双点触摸每次移动时的距离,
      
  91.         //而m_fTouchLength是双点开始时的距离,会根据move过程中距离与初始距离的比例进行缩放
      
  92.         else if (m_pTouches->count() == 2 && !m_bDragging)  
  93.         {  
  94.             const float len = ccpDistance(m_pContainer->convertTouchToNodeSpace((CCTouch*)m_pTouches->objectAtIndex(0)),  
  95.                                             m_pContainer->convertTouchToNodeSpace((CCTouch*)m_pTouches->objectAtIndex(1)));  
  96.             this->setZoomScale(this->getZoomScale()*len/m_fTouchLength);  
  97.         }  
  98.     }  
  99. }  

单点触摸时,调用了一个函数叫setContentOffset。下面继续分析contentOffset。

setContentOffset

  1. void CCScrollView::setContentOffset(CCPoint offset, bool animated/* = false*/)  
  2. {  
  3.     //默认情况,不做处理   
  4.     if (animated)  
  5.     { //animate scrolling
      
  6.         this->setContentOffsetInDuration(offset, BOUNCE_DURATION);  
  7.     }   
  8.     //好玩的东西哦   
  9.     else  
  10.     { //set the container position directly
      
  11.         //是否做越界处理,什么是越界,就是当你拖动整个容器时,如果已经到了容器的边界,还能不能再拖动,可以通过set函数进行设置
      
  12.         if (!m_bBounceable)  
  13.         {  
  14.             const CCPoint minOffset = this->minContainerOffset();  
  15.             const CCPoint maxOffset = this->maxContainerOffset();  
  16.               
  17.             offset.x = MAX(minOffset.x, MIN(maxOffset.x, offset.x));  
  18.             offset.y = MAX(minOffset.y, MIN(maxOffset.y, offset.y));  
  19.   
  20.               
  21.         }  
  22.         //CCLOG("The offset x is %f , y is %f",offset.x,offset.y);
      
  23.         m_pContainer->setPosition(offset);  
  24.   
  25.         //伟大的delegate来了,当你在滚动过程中想做除了基本界面滚动的额外操作时,请根据自己的不同情况,实现该delegate~完美的依赖抽象的设计,nice
      
  26.         if (m_pDelegate != NULL)  
  27.         {  
  28.             m_pDelegate->scrollViewDidScroll(this);     
  29.         }  
  30.     }  
  31. }  

双点触摸时,调用了一个重要的函数setZoomScale。

setZoomScale

  1. void CCScrollView::setZoomScale(float s)  
  2. {  
  3.     if (m_pContainer->getScale() != s)  
  4.     {  
  5.         CCPoint oldCenter, newCenter;  
  6.         CCPoint center;  
  7.         //设置缩放中心   
  8.         if (m_fTouchLength == 0.0f)   
  9.         {  
  10.             center = ccp(m_tViewSize.width*0.5f, m_tViewSize.height*0.5f);  
  11.             center = this->convertToWorldSpace(center);  
  12.         }  
  13.         else  
  14.         {  
  15.             center = m_tTouchPoint;  
  16.         }  
  17.         //缩放后中心的位置相对于world坐标系会产生offset,这里将offset进行计算
      
  18.         oldCenter = m_pContainer->convertToNodeSpace(center);  
  19.         m_pContainer->setScale(MAX(m_fMinScale, MIN(m_fMaxScale, s)));  
  20.         newCenter = m_pContainer->convertToWorldSpace(oldCenter);  
  21.           
  22.         const CCPoint offset = ccpSub(center, newCenter);  
  23.         //delegate的又一次出现
      
  24.         if (m_pDelegate != NULL)  
  25.         {  
  26.             m_pDelegate->scrollViewDidZoom(this);  
  27.         }  
  28.         //将产生的offset进行处理   
  29.         this->setContentOffset(ccpAdd(m_pContainer->getPosition(),offset));  
  30.     }  
  31. }  

3.3 ccTouchEnded

能坚持看到这里,已经可以看见胜利的曙光了,曙光。。。

  1. void CCScrollView::ccTouchEnded(CCTouch* touch, CCEvent* event)  
  2. {  
  3.     if (!this->isVisible())  
  4.     {  
  5.         return;  
  6.     }  
  7.     //将touch从pTouches中移除
      
  8.     if (m_pTouches->containsObject(touch))  
  9.     {  
  10.         //当剩下一个touch时,需要在每一帧调用方法deaccelerateScrolling
      
  11.         if (m_pTouches->count() == 1 && m_bTouchMoved)  
  12.         {  
  13.             this->schedule(schedule_selector(CCScrollView::deaccelerateScrolling));  
  14.         }  
  15.         m_pTouches->removeObject(touch);  
  16.         //CCLOG("CCScrollView::ccTouchEnded %d", m_pTouches->count());
      
  17.         //m_pDelegate->scrollViewDidStop(this);
      
  18.     }   
  19.     //没有touch时,需要设置状态   
  20.     if (m_pTouches->count() == 0)  
  21.     {  
  22.         m_bDragging = false;      
  23.         m_bTouchMoved = false;  
  24.     }  
  25. }  

 

deaccelerateScrolling

在这个函数中,有一个地方没有理解,求大神指点

  1. void CCScrollView::deaccelerateScrolling(float dt)  
  2. {  
  3.     //如果刚好在帧开始前 又有一个触摸点发生了began,造成了滚动状态,则取消并返回
      
  4.     if (m_bDragging)  
  5.     {  
  6.         this->unschedule(schedule_selector(CCScrollView::deaccelerateScrolling));  
  7.         return;  
  8.     }  
  9.       
  10.     //好玩的东西来咯   
  11.       
  12.     float newX, newY;  
  13.     CCPoint maxInset, minInset;  
  14.     CCLOG("The end distance is %f",m_tScrollDistance.x);  
  15.     //这里我不清楚为啥要出来,我用输出发现在move中,已经将此offset设置过了,不知为何还要设置,求大神解答。
      
  16.     m_pContainer->setPosition(ccpAdd(m_pContainer->getPosition(), m_tScrollDistance));  
  17.       
  18.     //是否允许越界,获得的inset信息   
  19.     if (m_bBounceable)  
  20.     {  
  21.         maxInset = m_fMaxInset;  
  22.         minInset = m_fMinInset;  
  23.     }  
  24.     else  
  25.     {  
  26.         maxInset = this->maxContainerOffset();  
  27.         minInset = this->minContainerOffset();  
  28.     }  
  29.       
  30.     //check to see if offset lies within the inset bounds
      
  31.     newX     = MIN(m_pContainer->getPosition().x, maxInset.x);  
  32.     newX     = MAX(newX, minInset.x);  
  33.     newY     = MIN(m_pContainer->getPosition().y, maxInset.y);  
  34.     newY     = MAX(newY, minInset.y);  
  35.       
  36.     newX = m_pContainer->getPosition().x;  
  37.     newY = m_pContainer->getPosition().y;  
  38.       
  39.     m_tScrollDistance     = ccpSub(m_tScrollDistance, ccp(newX - m_pContainer->getPosition().x, newY - m_pContainer->getPosition().y));  
  40.     m_tScrollDistance     = ccpMult(m_tScrollDistance, SCROLL_DEACCEL_RATE);  
  41.     this->setContentOffset(ccp(newX,newY));  
  42.       
  43.     if ((fabsf(m_tScrollDistance.x) <= SCROLL_DEACCEL_DIST &&  
  44.          fabsf(m_tScrollDistance.y) <= SCROLL_DEACCEL_DIST) ||  
  45.         newY > maxInset.y || newY < minInset.y ||  
  46.         newX > maxInset.x || newX < minInset.x ||  
  47.         newX == maxInset.x || newX == minInset.x ||  
  48.         newY == maxInset.y || newY == minInset.y)  
  49.     {  
  50.         this->unschedule(schedule_selector(CCScrollView::deaccelerateScrolling));  
  51.         //越界动画,从越界部分慢慢移动到不越界状态的函数。
      
  52.         this->relocateContainer(true);  
  53.         //伟大的delegate。。。
      
  54.         m_pDelegate->scrollViewDidStop(this);  
  55.           
  56.           
  57.           
  58.     }  
  59. }  


 

relocateContainer

  1. void CCScrollView::relocateContainer(bool animated)  
  2. {  
  3.     //这个函数将容器从当前地方通过动画移动到玩家自己设置的允许偏移的地方
      
  4.     CCPoint oldPoint, min, max;  
  5.     float newX, newY;  
  6.     //偏移值自己可以设置   
  7.     min = this->minContainerOffset();  
  8.     max = this->maxContainerOffset();  
  9.       
  10.     oldPoint = m_pContainer->getPosition();  
  11.   
  12.     newX     = oldPoint.x;  
  13.     newY     = oldPoint.y;  
  14.     if (m_eDirection == kCCScrollViewDirectionBoth || m_eDirection == kCCScrollViewDirectionHorizontal)  
  15.     {  
  16.         newX     = MAX(newX, min.x);  
  17.         newX     = MIN(newX, max.x);  
  18.     }  
  19.   
  20.     if (m_eDirection == kCCScrollViewDirectionBoth || m_eDirection == kCCScrollViewDirectionVertical)  
  21.     {  
  22.         newY     = MIN(newY, max.y);  
  23.         newY     = MAX(newY, min.y);  
  24.     }  
  25.     //还是调用setContentOffset,但是需要动画
      
  26.     if (newY != oldPoint.y || newX != oldPoint.x)  
  27.     {  
  28.         this->setContentOffset(ccp(newX, newY), animated);  
  29.     }  
  30. }  

setContentOffsetInDuration

  1. void CCScrollView::setContentOffsetInDuration(CCPoint offset, float dt)  
  2. {  
  3.     CCFiniteTimeAction *scroll, *expire;  
  4.     //滚动的偏移动画   
  5.     scroll = CCMoveTo::create(dt, offset);  
  6.     //滚动完成后的动画(负责停止performedAnimatedScroll,并且调用delegate)
      
  7.     expire = CCCallFuncN::create(this, callfuncN_selector(CCScrollView::stoppedAnimatedScroll));  
  8.     m_pContainer->runAction(CCSequence::create(scroll, expire, NULL));  
  9.     //负责不停调用delegate   
  10.     this->schedule(schedule_selector(CCScrollView::performedAnimatedScroll));  
  11. }  


4.小结

看到这里,CCScrollView里面属于自己独有部分的东西基本已经看完。可以看出:
1.CCScrollView支持两种操作,滚动和缩放。
2.CCScrollView通过delegate将数据与界面解耦。
3.CCScrollView本质是一个CClayer,他展示的是自己内部的container,并且CCScrollView的触摸以及展示是根据ViewSize 还不是本身的SIze决定的。
【上篇】
【下篇】

抱歉!评论已关闭.