代码参考于:http://www.allareone.cn/?p=36#more-36
非常感谢!
先把大神的文章摘取如下:
============================================================
由于项目需求,但是cocos2dx的却没有提供画扇形和环形的函数,于是乎决定自己写一个画扇形的函数。
基于cocos2dx-3.3版本继承于DrawNode类
就不详解了,感情都在代码里了:), 有需要请取走
用法示例: drawSolidSector(Vec2(200,200), Vec2(1,1), 100, 150, M_PI, 40, Color4F(1, 0, 0, 1));
void MyDrawNode::drawSolidSector(const Vec2 &orign,const Vec2 &beginVec, const float radius1, const float radius2, const float radian, const int segments, const cocos2d::Color4F &color)
{
float angle = atanf(beginVec.x / beginVec.y);
angle = beginVec.y<0? angle+M_PI: angle;
float coef = radian/segments;
Vec2 *vertices1 = new (std::nothrow) Vec2[segments+1];
if( ! vertices1 )
return;
Vec2 *vertices2 = new (std::nothrow) Vec2[segments+1];
if( ! vertices2 )
return;
for(unsigned int i = 0;i <= segments; i++)
{
float rads = i*coef;
GLfloat j = radius1 * cosf(rads + angle) + orign.y;
GLfloat k = radius1 * sinf(rads + angle) + orign.x;
vertices1[i].x = k;
vertices1[i].y = j;
GLfloat l = radius2 * cosf(rads + angle) + orign.y;
GLfloat m = radius2 * sinf(rads + angle) + orign.x;
vertices2[i].x = m;
vertices2[i].y = l;
}
V2F_C4B_T2F_Triangle *triangles = new V2F_C4B_T2F_Triangle[segments*2];
int triCount = 0;
for (int i=0; i1];
triangles[triCount].a.vertices = vertices1[i];
triangles[triCount].b.vertices = vertices1[i+1];
triangles[triCount++].c.vertices = vertices2[i+1];
}
for (int i=0; i2; i++) {
drawTriangle(triangles[i].a.vertices, triangles[i].b.vertices, triangles[i].c.vertices, color);
}
CC_SAFE_DELETE_ARRAY(vertices1);
CC_SAFE_DELETE_ARRAY(vertices2);
CC_SAFE_DELETE_ARRAY(triangles);
}
============================================================
饼状图/抽奖的效果
代码实现:
auto drawNode = DrawNode::create();
//测试的角度
//float radian[] = { 15.0f, 30.0f, 45.0f, 75.0f, 90.0f, 105.0f };
float radian[] = { 60.0f, 60.0f, 60.0f, 60.0f, 60.0f, 60.0f };
//扇形半径
float RADIUS = 300.0f;
//坐标偏移量
float beginVec = 0.0f;
//字体偏移量
float middleVec = 0.0f;
//旋转字体
float rotation = 0.0f;
for (int i = 0; i < sizeof(radian) / sizeof(radian[0]); i++)
{
//坐标
float x = sin(beginVec);
float y = cos(beginVec);
//颜色
float r = rand_0_1();
float g = rand_0_1();
float b = rand_0_1();
//画弧形
drawNode->drawSolidSector(Vec2(900, 400), Vec2(x, y), RADIUS, 0, radian[i] * M_PI / 180.0f, 200, Color4F(r, g, b, 1));
beginVec = beginVec + radian[i] * M_PI / 180.0f;
//度数字体
string txt = StringUtils::format("%.f", radian[i]);
auto text = Text::create(txt, "", 30.0f);
middleVec = radian[i] / 2 * M_PI / 180.0f;
text->setPosition(Vec2(900 + RADIUS/2 * sin(beginVec - middleVec), 400 + RADIUS/2 * cos(beginVec - middleVec)));
text->setRotation(rotation + radian[i] / 2); //旋转
rotation += radian[i];
addChild(text, 2);
}
addChild(drawNode, 1);