cocos2d-x版本:2.1.3this
原理:當出現屏幕觸摸事件時,記錄觸摸點的座標,而後經過重載draw()方法,這個方法每幀會畫一次屏幕,咱們在該方法中將記錄的點畫出來。spa
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" #include "Box2D/Box2D.h" #include "SimpleAudioEngine.h" USING_NS_CC; class HelloWorld : public cocos2d::CCLayer { public: virtual bool init(); static cocos2d::CCScene* scene(); void menuCloseCallback(CCObject* pSender); CREATE_FUNC(HelloWorld); public : CCPointArray*pArray; virtual void draw(); virtual bool ccTouchBegan(CCTouch*touch,CCEvent*event);//觸摸開始 virtual void ccTouchMoved(CCTouch*touch,CCEvent*event);//觸摸移動 virtual void ccTouchEnded(CCTouch*touch,CCEvent*event);//觸摸結束 virtual void registerWithTouchDispatcher(void);//註冊單點觸摸 }; #endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h" using namespace cocos2d; CCScene* HelloWorld::scene() { CCScene * scene = NULL; do { scene = CCScene::create(); CC_BREAK_IF(! scene); HelloWorld *layer = HelloWorld::create(); CC_BREAK_IF(! layer); scene->addChild(layer); } while (0); return scene; } bool HelloWorld::init() { bool bRet = false; do { CC_BREAK_IF(! CCLayer::init()); CCMenuItemImage *pCloseItem = CCMenuItemImage::create( "CloseNormal.png", "CloseSelected.png", this, menu_selector(HelloWorld::menuCloseCallback)); CC_BREAK_IF(! pCloseItem); pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20)); CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); pMenu->setPosition(CCPointZero); CC_BREAK_IF(! pMenu); this->addChild(pMenu, 1); pArray=CCPointArray::create(20); pArray->retain();//增長引用計數,否則會被自動釋放 this->setTouchEnabled(true); bRet = true; } while (0); return bRet; } void HelloWorld::draw(){ //畫直線 glLineWidth(5); ccDrawColor4B(0,255,255,255); //是否是最後一個點 bool isFirstPoint=false; if(pArray!=NULL){ int count=pArray->count(); for(int i=0;i<count;i++){ //取出一個座標 CCPoint point=pArray->getControlPointAtIndex(i); //判斷是否是鬆手時的座標 if(point.equals(ccp(-1,-1))){ isFirstPoint=true; }else{ //若是是第一個座標點或鬆手時的座標點畫點,不然畫直線 if(i==0||isFirstPoint){ ccDrawPoint(ccp(point.x,point.y)); isFirstPoint=false; }else{ CCPoint ps=pArray->getControlPointAtIndex(i-1); ccDrawLine(ccp(point.x,point.y),ccp(ps.x,ps.y )); } } } } }; //觸摸開始 bool HelloWorld::ccTouchBegan(CCTouch*touch,CCEvent*event){ CCPoint point=touch->getLocationInView(); point=CCDirector::sharedDirector()->convertToGL(point); pArray->addControlPoint(point); return true; }; //觸摸移動 void HelloWorld::ccTouchMoved(CCTouch*touch,CCEvent*event){ CCPoint point =touch->getLocationInView(); point=CCDirector::sharedDirector()->convertToGL(point); pArray->addControlPoint(point); }; //觸摸結束 void HelloWorld::ccTouchEnded(CCTouch*touch,CCEvent*event){ pArray->addControlPoint(ccp(-1,-1)); }; //註冊單點觸摸 void HelloWorld::registerWithTouchDispatcher(void){ CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true); }; void HelloWorld::menuCloseCallback(CCObject* pSender) { //pArray->removeAllObjects(); }
最後想清除全部的點,實現清空畫板的效果,可是沒完成。code