这篇继续写scroll,不过这次不是用scrollView这个控件,而是自己编写一段代码实现拖动图片。假想有一张很大的地图,然后屏幕只能显示它的一角,这时候就要通过拖动来查看其他部分。本来是要用scrollView实现这个功能,可用起来始终那么别扭,这不,上午一气之下自己搞了个可以拖动图片的代码。
一、首先在init中添加自己要实现拖动到图片。
- bool HelloWorld::init()
- {
- bool bRet = false;
- do
- {
- CC_BREAK_IF(! CCLayer::init());
-
- CCSize size = CCDirector::sharedDirector()->getWinSize();
-
-
- sprite = CCSprite::create("map_bg.png");
- this->addChild(sprite);
- sprite->setPosition(ccp(size.width/2,size.height/2));
- sprite->setAnchorPoint(ccp(0.5,0.5));
-
-
- setTouchEnabled(true);
-
- bRet = true;
- } while (0);
-
- return bRet;
- }
二、真正实现拖动图片的代码:
- void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
- {
- CCSetIterator it = pTouches->begin();
- CCTouch* touch = (CCTouch*)(*it);
-
-
- m_tBeginPos = touch->getLocation();
- }
-
- void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
- {
- CCSetIterator it = pTouches->begin();
- CCTouch* touch = (CCTouch*)(*it);
-
- CCSize size = CCDirector::sharedDirector()->getWinSize();
-
- CCPoint touchLocation = touch->getLocation();
- float nMoveY = touchLocation.y - m_tBeginPos.y;
- float nMoveX = touchLocation.x - m_tBeginPos.x;
-
-
- CCPoint curPos = sprite->getPosition();
-
- CCPoint nextPos = ccp(curPos.x + nMoveX, curPos.y + nMoveY);
-
-
- float maxMoveY = sprite->getContentSize().height/2 - size.height/2;
- float maxMoveX = sprite->getContentSize().width/2 - size.width/2;
-
- sprite->setPosition(nextPos);
- m_tBeginPos = touchLocation;
-
-
- HelloWorld::judgeHV(nextPos,maxMoveY);
- HelloWorld::judgeLR(nextPos,maxMoveX);
- }
三、judgeHV跟judgeLR是为了防止图片被拖动出边界,出现黑边。
- void HelloWorld::judgeHV(CCPoint nextPos,float max)
- {
- CCSize size = CCDirector::sharedDirector()->getWinSize();
-
-
- if (nextPos.y <(size.height/2-max))
- {
-
- sprite->setPositionY(size.height/2-max);
- return;
- }
-
- if(nextPos.y > (size.height/2 + max))
- {
- sprite->setPositionY(size.height/2 + max);
- return;
- }
- }
-
- void HelloWorld::judgeLR(CCPoint nextPos,float max)
- {
- CCSize size = CCDirector::sharedDirector()->getWinSize();
-
- if(nextPos.x < (size.width/2 - max))
- {
- sprite->setPositionX(size.width/2 - max);
- return;
- }
-
- if(nextPos.x > (size.width/2 + max))
- {
- sprite->setPositionX(size.width/2 + max);
- return;
- }
- }
恩,这样就成功了。简单吧。