前端之家收集整理的这篇文章主要介绍了
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));//根据数组里的点来画线;
}
}
}
}
}