~~~~我的生活,我的点点滴滴!!
关于cocos2d-x 3.x 版本的绘图方法有两种:
1、使用DrawNode类绘制自定义图形。
2、继承Layer类重写draw()方法。
以上两种方法都可以绘制自定义图形,根据自己的需要选择合适的方法,这里我们只讨论第一种方法,第二种方法涉及到opengl的知识,等到以后开专题去学习!!
我们先来简单的看看DrawNode提供的API接口:
class CC_DLL DrawNode : public Node { public: //初始化一个DrawNode对象,然后被addChild添加进去就ok了 static DrawNode* create(); //画实心圆,参数分别是圆心位置、圆半径、圆填充颜色,如果要画空心圆,就把圆当多边形画(这个多边形点数很多而已) void drawDot(const Vec2 &pos, float radius, const Color4F &color); //画线段,从from到to,2*radius是线段的宽度和radius是线段两头半圆形的半径 void drawSegment(const Vec2 &from, const Vec2 &to, float radius, const Color4F &color); //画多边形,verts为点集,count为点数,fillColor为填充颜色,borderWidth为边缘线宽,borderColor为边缘线颜色 void drawPolygon(Vec2 *verts, int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor); //画三角形,三人顶点及其填充色 void drawTriangle(const Vec2 &p1, const Vec2 &p2, const Vec2 &p3, const Color4F &color); //画三次贝塞尔曲线 void drawCubicBezier(const Vec2& from, const Vec2& control1, const Vec2& control2, const Vec2& to, unsigned int segments, const Color4F &color); //画二次贝塞尔曲线 void drawQuadraticBezier(const Vec2& from, const Vec2& control, const Vec2& to, unsigned int segments, const Color4F &color); /** Clear the geometry in the node's buffer. */ void clear(); /** * @js NA * @lua NA */ const BlendFunc& getBlendFunc() const; /** * @code * When this function bound into js or lua,the parameter will be changed * In js: var setBlendFunc(var src, var dst) * @endcode * @lua NA */ void setBlendFunc(const BlendFunc &blendFunc); void onDraw(const Mat4 &transform, uint32_t flags); // 新的绘图渲染函数 virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override; CC_CONSTRUCTOR_ACCESS: DrawNode(); virtual ~DrawNode(); virtual bool init(); protected: void ensureCapacity(int count); GLuint _vao; GLuint _vbo; int _bufferCapacity; GLsizei _bufferCount; V2F_C4B_T2F *_buffer; BlendFunc _blendFunc; CustomCommand _customCommand; bool _dirty; private: CC_DISALLOW_COPY_AND_ASSIGN(DrawNode); };
auto s = Director::getInstance()->getWinSize(); //创建DrawNode对象 DrawNode *drawNode = DrawNode::create(); //加入场景就OK this->addChild(drawNode, 20); //画实心圆 drawNode->drawDot(Vec2(60, 100), 20, Color4F(0.5,0.6,0,1)); //画线段 drawNode->drawSegment(Vec2(100,100), Vec2(150,220), 0.5, Color4F(0,1,0,1)); // 画多边形 Vec2 points[] = { Vec2(200,200), Vec2(300,300), Vec2(400,150), Vec2(250,100) }; drawNode->drawPolygon(points, sizeof(points)/sizeof(points[0]), Color4F(1,0,0,0.5), 2, Color4F(0,0,1,1)); // 画三角形 drawNode->drawTriangle(Vec2(140, 70), Vec2(210, 130), Vec2(180, 40), Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5)); // 画二次贝塞尔曲线 drawNode->drawQuadraticBezier(Vec2(s.width - 150, s.height - 150), Vec2(s.width - 70, s.height - 10), Vec2(s.width - 10, s.height - 10), 10, Color4F(1, 0, 0, 1)); // 画三次贝塞尔曲线 drawNode->drawCubicBezier(Vec2(s.width - 250, 40), Vec2(s.width - 70, 100), Vec2(s.width - 30, 250), Vec2(s.width - 10, s.height - 50), 10, Color4F(0, 1, 0, 1));