cocos2d-x 画笔实现

#include "drawPaint.h"

int drawPaint::_penBold = 3;
bool drawPaint::_isTouchDraw = false;
CCScene * drawPaint::scene()
{
	CCScene * s = CCScene::create();
	CCLayer * layer = drawPaint::create();
	s->addChild(layer);
	return s;
}

bool drawPaint::init()
{
	bool bRet = false;
	do 
	{
		CC_BREAK_IF(!CCLayer::init());//这里不加冒号很容易出错;要注意;
		//画笔创建;
		pen = CCSprite::create("pen.png");
		pen->setVisible(false);
		pen->setAnchorPoint(ccp(0,0));
		addChild(pen);

		//注册触屏事件;
		CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,false);

		bRet = true;
	} while (0);

	return bRet;
}
bool drawPaint::ccTouchBegan(CCTouch *pTouch,CCEvent *pEvent)
{
	if (_isTouchDraw)
	{
		_point.push_back(pTouch->getLocation());//存入第一个点:
		pen->setVisible(true);//让画笔显示;
		pen->setPosition(pTouch->getLocation());//设置画笔位置;
	}		
	return _isTouchDraw;
}

void drawPaint::ccTouchMoved(CCTouch *pTouch,CCEvent *pEvent)
{
	//移动的过程中记录点的坐标,并存放到数组中;
	_point.push_back(pTouch->getLocation());
	pen->setPosition(pTouch->getLocation());
}
void drawPaint::ccTouchEnded(CCTouch * pTouch,CCEvent * pEvent)
{
	pen->setVisible(false);//让画笔消失;
	touchEndPos = ccp(-1,-1);//随便存一个在屏幕外的点作为结束点;
	_point.push_back(touchEndPos);//把结束点存放到数组里;

}

//根据存放的点来绘制图片;
void drawPaint::draw()
{
	
	CCLayer::draw();
	ccDrawColor4B(255,255,255);//颜色;
	glLineWidth(_penBold);//粗细;
	if (_point.size()!=0)
	{
		int count = _point.size();//记录点的个数;
		static bool isFirstPoint = false;//是否是第一个点;
		for (int i = 0; i < count;++i)
		{
			//获取点的位置;
			CCPoint pos = _point[i];
			if (pos.equals(touchEndPos))//检测结束点是否和数组尾点相等;
			{
				isFirstPoint = true;
			}
			else
			{
				if (isFirstPoint || i == 0)
				{
					ccDrawPoint(ccp(pos.x,pos.y));//i= 0时,画第一个点;
					isFirstPoint = false;
				}
				else
				{
					CCPoint p = _point[i - 1];// i-1个,不能让数组越界;
					ccDrawLine(ccp(pos.x,pos.y),ccp(p.x,p.y));//根据数组里的点来画线;
				}
			}
		}
	
	}

}

相关文章

操作步骤 1、创建cocos2d-x工程 2、新建 Scene1.cpp Scene1.h Scene1.h代码 #ifndef __SCENE1_H__#defi...
开发环境:OS(WINDOWS 8.1 X64 企业版) cocos2d-x 2.2.1 vs2010 想给vs安装上cocos的模版,执行Install...
把创建项目做成一个批处理,当创建项目时可以省时省力很多。 操作步骤 1、在 E:cocos2d-x-2.2.1toolspr...
https://www.cnblogs.com/JiaoQing/p/3906780.html 四个响应函数 1 EventListenerPhysicsContact* evC...
转载于 http://www.cnblogs.com/kenkofox/p/3926797.html 熟悉js的dom事件或者flash事件的,基本都能立...
ScrollView(滚动容器)加载大量item时会导致游戏界面的卡顿,严重时整个界面会出现卡死的情况。最近项...