CCScrollView.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. /****************************************************************************
  2. Copyright (c) 2012 cocos2d-x.org
  3. Copyright (c) 2010 Sangwoo Im
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "CCScrollView.h"
  22. #include "platform/CCDevice.h"
  23. #include "2d/CCActionInstant.h"
  24. #include "2d/CCActionInterval.h"
  25. #include "2d/CCActionTween.h"
  26. #include "base/CCDirector.h"
  27. #include "base/CCEventDispatcher.h"
  28. #include "renderer/CCRenderer.h"
  29. #include <algorithm>
  30. NS_CC_EXT_BEGIN
  31. #define SCROLL_DEACCEL_RATE 0.95f
  32. #define SCROLL_DEACCEL_DIST 1.0f
  33. #define BOUNCE_DURATION 0.15f
  34. #define INSET_RATIO 0.2f
  35. #define MOVE_INCH 7.0f/160.0f
  36. #define BOUNCE_BACK_FACTOR 0.35f
  37. static float convertDistanceFromPointToInch(float pointDis)
  38. {
  39. auto glview = Director::getInstance()->getOpenGLView();
  40. float factor = ( glview->getScaleX() + glview->getScaleY() ) / 2;
  41. return pointDis * factor / Device::getDPI();
  42. }
  43. ScrollView::ScrollView()
  44. : _delegate(nullptr)
  45. , _direction(Direction::BOTH)
  46. , _dragging(false)
  47. , _container(nullptr)
  48. , _touchMoved(false)
  49. , _bounceable(false)
  50. , _clippingToBounds(false)
  51. , _touchLength(0.0f)
  52. , _minScale(0.0f)
  53. , _maxScale(0.0f)
  54. , _scissorRestored(false)
  55. , _touchListener(nullptr)
  56. , _animatedScrollAction(nullptr)
  57. {
  58. }
  59. ScrollView::~ScrollView()
  60. {
  61. }
  62. ScrollView* ScrollView::create(Size size, Node* container/* = nullptr*/)
  63. {
  64. ScrollView* pRet = new (std::nothrow) ScrollView();
  65. if (pRet && pRet->initWithViewSize(size, container))
  66. {
  67. pRet->autorelease();
  68. }
  69. else
  70. {
  71. CC_SAFE_DELETE(pRet);
  72. }
  73. return pRet;
  74. }
  75. ScrollView* ScrollView::create()
  76. {
  77. ScrollView* pRet = new (std::nothrow) ScrollView();
  78. if (pRet && pRet->init())
  79. {
  80. pRet->autorelease();
  81. }
  82. else
  83. {
  84. CC_SAFE_DELETE(pRet);
  85. }
  86. return pRet;
  87. }
  88. bool ScrollView::initWithViewSize(Size size, Node *container/* = nullptr*/)
  89. {
  90. if (Layer::init())
  91. {
  92. _container = container;
  93. if (!this->_container)
  94. {
  95. _container = Layer::create();
  96. _container->setIgnoreAnchorPointForPosition(false);
  97. _container->setAnchorPoint(Vec2(0.0f, 0.0f));
  98. }
  99. this->setViewSize(size);
  100. setTouchEnabled(true);
  101. _touches.reserve(EventTouch::MAX_TOUCHES);
  102. _delegate = nullptr;
  103. _bounceable = true;
  104. _clippingToBounds = true;
  105. //_container->setContentSize(Size::ZERO);
  106. _direction = Direction::BOTH;
  107. _container->setPosition(0.0f, 0.0f);
  108. _touchLength = 0.0f;
  109. this->addChild(_container);
  110. _minScale = _maxScale = 1.0f;
  111. return true;
  112. }
  113. return false;
  114. }
  115. bool ScrollView::init()
  116. {
  117. return this->initWithViewSize(Size(200, 200), nullptr);
  118. }
  119. bool ScrollView::isNodeVisible(Node* node)
  120. {
  121. const Vec2 offset = this->getContentOffset();
  122. const Size size = this->getViewSize();
  123. const float scale = this->getZoomScale();
  124. Rect viewRect;
  125. viewRect = Rect(-offset.x/scale, -offset.y/scale, size.width/scale, size.height/scale);
  126. return viewRect.intersectsRect(node->getBoundingBox());
  127. }
  128. void ScrollView::pause(Ref* /*sender*/)
  129. {
  130. _container->pause();
  131. auto& children = _container->getChildren();
  132. for(const auto &child : children) {
  133. child->pause();
  134. }
  135. }
  136. void ScrollView::resume(Ref* /*sender*/)
  137. {
  138. auto& children = _container->getChildren();
  139. for(const auto &child : children) {
  140. child->resume();
  141. }
  142. _container->resume();
  143. }
  144. bool ScrollView::isTouchEnabled() const
  145. {
  146. return _touchListener != nullptr;
  147. }
  148. void ScrollView::setTouchEnabled(bool enabled)
  149. {
  150. _eventDispatcher->removeEventListener(_touchListener);
  151. _touchListener = nullptr;
  152. if (enabled)
  153. {
  154. _touchListener = EventListenerTouchOneByOne::create();
  155. _touchListener->setSwallowTouches(true);
  156. _touchListener->onTouchBegan = CC_CALLBACK_2(ScrollView::onTouchBegan, this);
  157. _touchListener->onTouchMoved = CC_CALLBACK_2(ScrollView::onTouchMoved, this);
  158. _touchListener->onTouchEnded = CC_CALLBACK_2(ScrollView::onTouchEnded, this);
  159. _touchListener->onTouchCancelled = CC_CALLBACK_2(ScrollView::onTouchCancelled, this);
  160. _eventDispatcher->addEventListenerWithSceneGraphPriority(_touchListener, this);
  161. }
  162. else
  163. {
  164. _dragging = false;
  165. _touchMoved = false;
  166. _touches.clear();
  167. }
  168. }
  169. void ScrollView::setContentOffset(Vec2 offset, bool animated/* = false*/)
  170. {
  171. if (animated)
  172. { //animate scrolling
  173. this->setContentOffsetInDuration(offset, BOUNCE_DURATION);
  174. }
  175. else
  176. { //set the container position directly
  177. if (!_bounceable)
  178. {
  179. const Vec2 minOffset = this->minContainerOffset();
  180. const Vec2 maxOffset = this->maxContainerOffset();
  181. offset.x = MAX(minOffset.x, MIN(maxOffset.x, offset.x));
  182. offset.y = MAX(minOffset.y, MIN(maxOffset.y, offset.y));
  183. }
  184. _container->setPosition(offset);
  185. if (_delegate != nullptr)
  186. {
  187. _delegate->scrollViewDidScroll(this);
  188. }
  189. }
  190. }
  191. void ScrollView::setContentOffsetInDuration(Vec2 offset, float dt)
  192. {
  193. FiniteTimeAction *scroll, *expire;
  194. if (_animatedScrollAction) {
  195. stopAnimatedContentOffset();
  196. }
  197. scroll = MoveTo::create(dt, offset);
  198. expire = CallFuncN::create(CC_CALLBACK_1(ScrollView::stoppedAnimatedScroll,this));
  199. _animatedScrollAction = _container->runAction(Sequence::create(scroll, expire, nullptr));
  200. _animatedScrollAction->retain();
  201. this->schedule(CC_SCHEDULE_SELECTOR(ScrollView::performedAnimatedScroll));
  202. }
  203. void ScrollView::stopAnimatedContentOffset() {
  204. stopAction(_animatedScrollAction);
  205. _animatedScrollAction->release();
  206. _animatedScrollAction = nullptr;
  207. stoppedAnimatedScroll(this);
  208. }
  209. Vec2 ScrollView::getContentOffset()
  210. {
  211. return _container->getPosition();
  212. }
  213. void ScrollView::setZoomScale(float s)
  214. {
  215. if (_container->getScale() != s)
  216. {
  217. Vec2 oldCenter, newCenter;
  218. Vec2 center;
  219. if (_touchLength == 0.0f)
  220. {
  221. center.set(_viewSize.width*0.5f, _viewSize.height*0.5f);
  222. center = this->convertToWorldSpace(center);
  223. }
  224. else
  225. {
  226. center = _touchPoint;
  227. }
  228. oldCenter = _container->convertToNodeSpace(center);
  229. _container->setScale(MAX(_minScale, MIN(_maxScale, s)));
  230. newCenter = _container->convertToWorldSpace(oldCenter);
  231. const Vec2 offset = center - newCenter;
  232. if (_delegate != nullptr)
  233. {
  234. _delegate->scrollViewDidZoom(this);
  235. }
  236. this->setContentOffset(_container->getPosition() + offset);
  237. }
  238. }
  239. float ScrollView::getZoomScale()
  240. {
  241. return _container->getScale();
  242. }
  243. void ScrollView::setZoomScale(float s, bool animated)
  244. {
  245. if (animated)
  246. {
  247. this->setZoomScaleInDuration(s, BOUNCE_DURATION);
  248. }
  249. else
  250. {
  251. this->setZoomScale(s);
  252. }
  253. }
  254. void ScrollView::setZoomScaleInDuration(float s, float dt)
  255. {
  256. if (dt > 0)
  257. {
  258. if (_container->getScale() != s)
  259. {
  260. ActionTween *scaleAction;
  261. scaleAction = ActionTween::create(dt, "zoomScale", _container->getScale(), s);
  262. this->runAction(scaleAction);
  263. }
  264. }
  265. else
  266. {
  267. this->setZoomScale(s);
  268. }
  269. }
  270. void ScrollView::updateTweenAction(float value, const std::string& /*key*/)
  271. {
  272. this->setZoomScale(value);
  273. }
  274. void ScrollView::setViewSize(Size size)
  275. {
  276. _viewSize = size;
  277. Layer::setContentSize(size);
  278. }
  279. Node * ScrollView::getContainer()
  280. {
  281. return this->_container;
  282. }
  283. void ScrollView::setContainer(Node * pContainer)
  284. {
  285. // Make sure that '_container' has a non-nullptr value since there are
  286. // lots of logic that use '_container'.
  287. if (nullptr == pContainer)
  288. return;
  289. this->removeAllChildrenWithCleanup(true);
  290. this->_container = pContainer;
  291. this->_container->setIgnoreAnchorPointForPosition(false);
  292. this->_container->setAnchorPoint(Vec2(0.0f, 0.0f));
  293. this->addChild(this->_container);
  294. this->setViewSize(this->_viewSize);
  295. }
  296. bool ScrollView::hasVisibleParents() const
  297. {
  298. auto parent = this->getParent();
  299. for( auto c = parent; c != nullptr; c = c->getParent() )
  300. {
  301. if( !c->isVisible() )
  302. {
  303. return false;
  304. }
  305. }
  306. return true;
  307. }
  308. void ScrollView::relocateContainer(bool animated)
  309. {
  310. Vec2 oldPoint, min, max;
  311. float newX, newY;
  312. min = this->minContainerOffset();
  313. max = this->maxContainerOffset();
  314. oldPoint = _container->getPosition();
  315. newX = oldPoint.x;
  316. newY = oldPoint.y;
  317. if (_direction == Direction::BOTH || _direction == Direction::HORIZONTAL)
  318. {
  319. newX = MAX(newX, min.x);
  320. newX = MIN(newX, max.x);
  321. }
  322. if (_direction == Direction::BOTH || _direction == Direction::VERTICAL)
  323. {
  324. newY = MIN(newY, max.y);
  325. newY = MAX(newY, min.y);
  326. }
  327. if (newY != oldPoint.y || newX != oldPoint.x)
  328. {
  329. this->setContentOffset(Vec2(newX, newY), animated);
  330. }
  331. }
  332. Vec2 ScrollView::maxContainerOffset()
  333. {
  334. Point anchorPoint = _container->isIgnoreAnchorPointForPosition()?Point::ZERO:_container->getAnchorPoint();
  335. float contW = _container->getContentSize().width * _container->getScaleX();
  336. float contH = _container->getContentSize().height * _container->getScaleY();
  337. return Vec2(anchorPoint.x * contW, anchorPoint.y * contH);
  338. }
  339. Vec2 ScrollView::minContainerOffset()
  340. {
  341. Point anchorPoint = _container->isIgnoreAnchorPointForPosition()?Point::ZERO:_container->getAnchorPoint();
  342. float contW = _container->getContentSize().width * _container->getScaleX();
  343. float contH = _container->getContentSize().height * _container->getScaleY();
  344. return Vec2(_viewSize.width - (1 - anchorPoint.x) * contW, _viewSize.height - (1 - anchorPoint.y) * contH);
  345. }
  346. void ScrollView::deaccelerateScrolling(float /*dt*/)
  347. {
  348. if (_dragging)
  349. {
  350. this->unschedule(CC_SCHEDULE_SELECTOR(ScrollView::deaccelerateScrolling));
  351. return;
  352. }
  353. float newX, newY;
  354. Vec2 maxInset, minInset;
  355. _container->setPosition(_container->getPosition() + _scrollDistance);
  356. if (_bounceable)
  357. {
  358. maxInset = _maxInset;
  359. minInset = _minInset;
  360. }
  361. else
  362. {
  363. maxInset = this->maxContainerOffset();
  364. minInset = this->minContainerOffset();
  365. }
  366. newX = _container->getPosition().x;
  367. newY = _container->getPosition().y;
  368. _scrollDistance = _scrollDistance * SCROLL_DEACCEL_RATE;
  369. this->setContentOffset(Vec2(newX,newY));
  370. if ((fabsf(_scrollDistance.x) <= SCROLL_DEACCEL_DIST &&
  371. fabsf(_scrollDistance.y) <= SCROLL_DEACCEL_DIST) ||
  372. ((_direction == Direction::BOTH || _direction == Direction::VERTICAL) && (newY >= maxInset.y || newY <= minInset.y)) ||
  373. ((_direction == Direction::BOTH || _direction == Direction::HORIZONTAL) && (newX >= maxInset.x || newX <= minInset.x)))
  374. {
  375. this->unschedule(CC_SCHEDULE_SELECTOR(ScrollView::deaccelerateScrolling));
  376. this->relocateContainer(true);
  377. }
  378. }
  379. void ScrollView::stoppedAnimatedScroll(Node * /*node*/)
  380. {
  381. this->unschedule(CC_SCHEDULE_SELECTOR(ScrollView::performedAnimatedScroll));
  382. // After the animation stopped, "scrollViewDidScroll" should be invoked, this could fix the bug of lack of tableview cells.
  383. if (_delegate != nullptr)
  384. {
  385. _delegate->scrollViewDidScroll(this);
  386. }
  387. }
  388. void ScrollView::performedAnimatedScroll(float /*dt*/)
  389. {
  390. if (_dragging)
  391. {
  392. this->unschedule(CC_SCHEDULE_SELECTOR(ScrollView::performedAnimatedScroll));
  393. return;
  394. }
  395. if (_delegate != nullptr)
  396. {
  397. _delegate->scrollViewDidScroll(this);
  398. }
  399. }
  400. const Size& ScrollView::getContentSize() const
  401. {
  402. return _container->getContentSize();
  403. }
  404. void ScrollView::setContentSize(const Size & size)
  405. {
  406. if (this->getContainer() != nullptr)
  407. {
  408. this->getContainer()->setContentSize(size);
  409. this->updateInset();
  410. }
  411. }
  412. void ScrollView::updateInset()
  413. {
  414. if (this->getContainer() != nullptr)
  415. {
  416. _maxInset = this->maxContainerOffset();
  417. _maxInset.set(_maxInset.x + _viewSize.width * INSET_RATIO,
  418. _maxInset.y + _viewSize.height * INSET_RATIO);
  419. _minInset = this->minContainerOffset();
  420. _minInset.set(_minInset.x - _viewSize.width * INSET_RATIO,
  421. _minInset.y - _viewSize.height * INSET_RATIO);
  422. }
  423. }
  424. /**
  425. * make sure all children go to the container
  426. */
  427. void ScrollView::addChild(Node * child, int zOrder, int tag)
  428. {
  429. if (_container != child) {
  430. _container->addChild(child, zOrder, tag);
  431. } else {
  432. Layer::addChild(child, zOrder, tag);
  433. }
  434. }
  435. void ScrollView::removeChild(Node* node, bool cleanup)
  436. {
  437. if(_container != node)
  438. {
  439. _container->removeChild(node, cleanup);
  440. }
  441. else
  442. {
  443. Layer::removeChild(node, cleanup);
  444. }
  445. }
  446. void ScrollView::removeAllChildrenWithCleanup(bool cleanup)
  447. {
  448. _container->removeAllChildrenWithCleanup(cleanup);
  449. Layer::removeAllChildrenWithCleanup(cleanup);
  450. }
  451. void ScrollView::removeAllChildren()
  452. {
  453. removeAllChildrenWithCleanup(true);
  454. }
  455. void ScrollView::addChild(Node * child, int zOrder, const std::string &name)
  456. {
  457. if (_container != child)
  458. {
  459. _container->addChild(child, zOrder, name);
  460. }
  461. else
  462. {
  463. Layer::addChild(child, zOrder, name);
  464. }
  465. }
  466. void ScrollView::beforeDraw()
  467. {
  468. //ScrollView don't support drawing in 3D space
  469. _beforeDrawCommand.init(_globalZOrder);
  470. _beforeDrawCommand.func = CC_CALLBACK_0(ScrollView::onBeforeDraw, this);
  471. Director::getInstance()->getRenderer()->addCommand(&_beforeDrawCommand);
  472. }
  473. /**
  474. * clip this view so that outside of the visible bounds can be hidden.
  475. */
  476. void ScrollView::onBeforeDraw()
  477. {
  478. if (_clippingToBounds)
  479. {
  480. _scissorRestored = false;
  481. Rect frame = getViewRect();
  482. auto glview = Director::getInstance()->getOpenGLView();
  483. if (glview->getVR() == nullptr) {
  484. if (glview->isScissorEnabled()) {
  485. _scissorRestored = true;
  486. _parentScissorRect = glview->getScissorRect();
  487. //set the intersection of _parentScissorRect and frame as the new scissor rect
  488. if (frame.intersectsRect(_parentScissorRect)) {
  489. float x = MAX(frame.origin.x, _parentScissorRect.origin.x);
  490. float y = MAX(frame.origin.y, _parentScissorRect.origin.y);
  491. float xx = MIN(frame.origin.x + frame.size.width, _parentScissorRect.origin.x + _parentScissorRect.size.width);
  492. float yy = MIN(frame.origin.y + frame.size.height, _parentScissorRect.origin.y + _parentScissorRect.size.height);
  493. glview->setScissorInPoints(x, y, xx - x, yy - y);
  494. }
  495. }
  496. else {
  497. glEnable(GL_SCISSOR_TEST);
  498. glview->setScissorInPoints(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
  499. }
  500. }
  501. }
  502. }
  503. void ScrollView::afterDraw()
  504. {
  505. _afterDrawCommand.init(_globalZOrder);
  506. _afterDrawCommand.func = CC_CALLBACK_0(ScrollView::onAfterDraw, this);
  507. Director::getInstance()->getRenderer()->addCommand(&_afterDrawCommand);
  508. }
  509. /**
  510. * retract what's done in beforeDraw so that there's no side effect to
  511. * other nodes.
  512. */
  513. void ScrollView::onAfterDraw()
  514. {
  515. if (_clippingToBounds)
  516. {
  517. auto glview = Director::getInstance()->getOpenGLView();
  518. if (glview->getVR() == nullptr) {
  519. if (_scissorRestored) {//restore the parent's scissor rect
  520. glview->setScissorInPoints(_parentScissorRect.origin.x, _parentScissorRect.origin.y, _parentScissorRect.size.width, _parentScissorRect.size.height);
  521. }
  522. else {
  523. glDisable(GL_SCISSOR_TEST);
  524. }
  525. }
  526. }
  527. }
  528. void ScrollView::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags)
  529. {
  530. // quick return if not visible
  531. if (!isVisible())
  532. {
  533. return;
  534. }
  535. uint32_t flags = processParentFlags(parentTransform, parentFlags);
  536. // IMPORTANT:
  537. // To ease the migration to v3.0, we still support the Mat4 stack,
  538. // but it is deprecated and your code should not rely on it
  539. Director* director = Director::getInstance();
  540. CCASSERT(nullptr != director, "Director is null when setting matrix stack");
  541. director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  542. director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
  543. this->beforeDraw();
  544. bool visibleByCamera = isVisitableByVisitingCamera();
  545. if (!_children.empty())
  546. {
  547. int i=0;
  548. // draw children zOrder < 0
  549. for( ; i < _children.size(); i++ )
  550. {
  551. Node *child = _children.at(i);
  552. if ( child->getLocalZOrder() < 0 )
  553. {
  554. child->visit(renderer, _modelViewTransform, flags);
  555. }
  556. else
  557. {
  558. break;
  559. }
  560. }
  561. // this draw
  562. if (visibleByCamera)
  563. this->draw(renderer, _modelViewTransform, flags);
  564. // draw children zOrder >= 0
  565. for( ; i < _children.size(); i++ )
  566. {
  567. Node *child = _children.at(i);
  568. child->visit(renderer, _modelViewTransform, flags);
  569. }
  570. }
  571. else if (visibleByCamera)
  572. {
  573. this->draw(renderer, _modelViewTransform, flags);
  574. }
  575. this->afterDraw();
  576. director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  577. }
  578. bool ScrollView::onTouchBegan(Touch* touch, Event* /*event*/)
  579. {
  580. if (!this->isVisible() || !this->hasVisibleParents())
  581. {
  582. return false;
  583. }
  584. Rect frame = getViewRect();
  585. //dispatcher does not know about clipping. reject touches outside visible bounds.
  586. if (_touches.size() > 2 ||
  587. _touchMoved ||
  588. !frame.containsPoint(touch->getLocation()))
  589. {
  590. return false;
  591. }
  592. if (std::find(_touches.begin(), _touches.end(), touch) == _touches.end())
  593. {
  594. _touches.push_back(touch);
  595. }
  596. if (_touches.size() == 1)
  597. { // scrolling
  598. _touchPoint = this->convertTouchToNodeSpace(touch);
  599. _touchMoved = false;
  600. _dragging = true; //dragging started
  601. _scrollDistance.setZero();
  602. _touchLength = 0.0f;
  603. }
  604. else if (_touches.size() == 2)
  605. {
  606. _touchPoint = (this->convertTouchToNodeSpace(_touches[0]).getMidpoint(
  607. this->convertTouchToNodeSpace(_touches[1])));
  608. _touchLength = _container->convertTouchToNodeSpace(_touches[0]).getDistance(
  609. _container->convertTouchToNodeSpace(_touches[1]));
  610. _dragging = false;
  611. }
  612. return true;
  613. }
  614. void ScrollView::onTouchMoved(Touch* touch, Event* /*event*/)
  615. {
  616. if (!this->isVisible())
  617. {
  618. return;
  619. }
  620. if (std::find(_touches.begin(), _touches.end(), touch) != _touches.end())
  621. {
  622. if (_touches.size() == 1 && _dragging)
  623. { // scrolling
  624. Vec2 moveDistance, newPoint;
  625. Rect frame;
  626. float newX, newY;
  627. frame = getViewRect();
  628. newPoint = this->convertTouchToNodeSpace(_touches[0]);
  629. moveDistance = newPoint - _touchPoint;
  630. float dis = 0.0f;
  631. if (_direction == Direction::VERTICAL)
  632. {
  633. dis = moveDistance.y;
  634. float pos = _container->getPosition().y;
  635. if (!(minContainerOffset().y <= pos && pos <= maxContainerOffset().y)) {
  636. moveDistance.y *= BOUNCE_BACK_FACTOR;
  637. }
  638. }
  639. else if (_direction == Direction::HORIZONTAL)
  640. {
  641. dis = moveDistance.x;
  642. float pos = _container->getPosition().x;
  643. if (!(minContainerOffset().x <= pos && pos <= maxContainerOffset().x)) {
  644. moveDistance.x *= BOUNCE_BACK_FACTOR;
  645. }
  646. }
  647. else
  648. {
  649. dis = sqrtf(moveDistance.x*moveDistance.x + moveDistance.y*moveDistance.y);
  650. float pos = _container->getPosition().y;
  651. if (!(minContainerOffset().y <= pos && pos <= maxContainerOffset().y)) {
  652. moveDistance.y *= BOUNCE_BACK_FACTOR;
  653. }
  654. pos = _container->getPosition().x;
  655. if (!(minContainerOffset().x <= pos && pos <= maxContainerOffset().x)) {
  656. moveDistance.x *= BOUNCE_BACK_FACTOR;
  657. }
  658. }
  659. if (!_touchMoved && fabs(convertDistanceFromPointToInch(dis)) < MOVE_INCH )
  660. {
  661. //CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y);
  662. return;
  663. }
  664. if (!_touchMoved)
  665. {
  666. moveDistance.setZero();
  667. }
  668. _touchPoint = newPoint;
  669. _touchMoved = true;
  670. if (_dragging)
  671. {
  672. switch (_direction)
  673. {
  674. case Direction::VERTICAL:
  675. moveDistance.set(0.0f, moveDistance.y);
  676. break;
  677. case Direction::HORIZONTAL:
  678. moveDistance.set(moveDistance.x, 0.0f);
  679. break;
  680. default:
  681. break;
  682. }
  683. newX = _container->getPosition().x + moveDistance.x;
  684. newY = _container->getPosition().y + moveDistance.y;
  685. _scrollDistance = moveDistance;
  686. this->setContentOffset(Vec2(newX, newY));
  687. }
  688. }
  689. else if (_touches.size() == 2 && !_dragging)
  690. {
  691. const float len = _container->convertTouchToNodeSpace(_touches[0]).getDistance(
  692. _container->convertTouchToNodeSpace(_touches[1]));
  693. this->setZoomScale(this->getZoomScale()*len/_touchLength);
  694. }
  695. }
  696. }
  697. void ScrollView::onTouchEnded(Touch* touch, Event* /*event*/)
  698. {
  699. if (!this->isVisible())
  700. {
  701. return;
  702. }
  703. auto touchIter = std::find(_touches.begin(), _touches.end(), touch);
  704. if (touchIter != _touches.end())
  705. {
  706. if (_touches.size() == 1 && _touchMoved)
  707. {
  708. this->schedule(CC_SCHEDULE_SELECTOR(ScrollView::deaccelerateScrolling));
  709. }
  710. _touches.erase(touchIter);
  711. }
  712. if (_touches.size() == 0)
  713. {
  714. _dragging = false;
  715. _touchMoved = false;
  716. }
  717. }
  718. void ScrollView::onTouchCancelled(Touch* touch, Event* /*event*/)
  719. {
  720. if (!this->isVisible())
  721. {
  722. return;
  723. }
  724. auto touchIter = std::find(_touches.begin(), _touches.end(), touch);
  725. if ( touchIter == _touches.end() )
  726. return;
  727. _touches.erase(touchIter);
  728. if (_touches.size() == 0)
  729. {
  730. _dragging = false;
  731. _touchMoved = false;
  732. }
  733. }
  734. Rect ScrollView::getViewRect()
  735. {
  736. Vec2 screenPos = this->convertToWorldSpace(Vec2::ZERO);
  737. float scaleX = this->getScaleX();
  738. float scaleY = this->getScaleY();
  739. for (Node *p = _parent; p != nullptr; p = p->getParent()) {
  740. scaleX *= p->getScaleX();
  741. scaleY *= p->getScaleY();
  742. }
  743. // Support negative scaling. Not doing so causes intersectsRect calls
  744. // (eg: to check if the touch was within the bounds) to return false.
  745. // Note, Node::getScale will assert if X and Y scales are different.
  746. if(scaleX<0.f) {
  747. screenPos.x += _viewSize.width*scaleX;
  748. scaleX = -scaleX;
  749. }
  750. if(scaleY<0.f) {
  751. screenPos.y += _viewSize.height*scaleY;
  752. scaleY = -scaleY;
  753. }
  754. return Rect(screenPos.x, screenPos.y, _viewSize.width*scaleX, _viewSize.height*scaleY);
  755. }
  756. NS_CC_EXT_END