带有Bezier的Cocos 2d-x圆角Corner

时间:2016-04-06 09:14:44

标签: c++ geometry cocos2d-x bezier

是否可以使用DrawNode对象绘制带圆角的Rect? 我认为使用Bezier曲线可以做到某些事情,但我已经做了一些尝试,我认为我无法处理它。

看看API我发现只有这两个函数:

drawQuadBezier (const Vec2 &origin, const Vec2 &control, const Vec2 &destination, unsigned int segments, const Color4F &color)

drawCubicBezier (const Vec2 &origin, const Vec2 &control1, const Vec2 &control2, const Vec2 &destination, unsigned int segments, const Color4F &color)

[回答后修改]

我在 Cocos2dx 中应用了答案,也许有人觉得这很有用:

(如果你不需要高精度,只需要对int进行一些转换)

auto MagicConst = 0.552;
auto position = 150;
auto R = 50;

Vec2 TopLeft = Vec2(position, position + R * 2);
Vec2 TopRight = Vec2(position + R * 2, position + R * 2);
Vec2 BottomRight = Vec2(position + R * 2, position);
Vec2 BottomLeft = Vec2(position, position);

Vec2 originTL = Vec2(TopLeft.x, TopLeft.y - R);
Vec2 originTR = Vec2(TopRight.x - R, TopRight.y);
Vec2 originBR = Vec2(BottomRight.x - R, BottomRight.y);
Vec2 originBL = Vec2(BottomLeft.x, BottomLeft.y + R);

Vec2 control1TL = Vec2(TopLeft.x, (int) (TopLeft.y - R * (1 - MagicConst)));
Vec2 control1TR = Vec2((int) (TopRight.x - R * (1 - MagicConst)), TopRight.y);
Vec2 control1BR = Vec2((int) (BottomRight.x - R * (1 - MagicConst)), BottomRight.y);
Vec2 control1BL = Vec2(BottomLeft.x, (int) (BottomLeft.y + R * (1 - MagicConst)));

Vec2 control2TL = Vec2((int) (TopLeft.x + R * (1 - MagicConst)), TopLeft.y);
Vec2 control2TR = Vec2(TopRight.x, (int) (TopRight.y - R * (1 - MagicConst)));
Vec2 control2BR = Vec2(BottomRight.x, (int) (BottomRight.y + R * (1 - MagicConst)));
Vec2 control2BL = Vec2((int) (BottomLeft.x + R * (1 - MagicConst)), BottomLeft.y);

Vec2 destinationTL = Vec2(TopLeft.x + R, TopLeft.y);
Vec2 destinationTR = Vec2(TopRight.x, TopRight.y - R);
Vec2 destinationBR = Vec2(BottomRight.x, BottomRight.y + R);
Vec2 destinationBL = Vec2(BottomLeft.x + R, BottomLeft.y);

auto roundCorner = DrawNode::create();
roundCorner->drawCubicBezier(originTL, control1TL, control2TL, destinationTL, 10, Color4F::RED);
roundCorner->drawCubicBezier(originTR, control1TR, control2TR, destinationTR, 10, Color4F::GREEN);
roundCorner->drawCubicBezier(originBR, control1BR, control2BR, destinationBR, 10, Color4F::YELLOW);
roundCorner->drawCubicBezier(originBL, control1BL, control2BL, destinationBL, 10, Color4F::WHITE);
addChild(roundCorner);

这将产生:http://i.stack.imgur.com/mdEOM.png

现在,您可以根据需要更改MagicConst以围绕角落。

例如MagicConst = 0.9http://i.stack.imgur.com/9V5cr.png

这就是我想要的结果! ;)(谢谢@Mbo)

(我无法发布嵌入图片):P

1 个答案:

答案 0 :(得分:3)

可以计算近似四分之一圆的立方贝塞尔曲线来制作圆角 轴对齐矩形(点TopLeft)和圆弧半径R的左上角示例:

编辑:更改了一些 - / +标志

MagicConst = 0.552
Bezier.origin.X = ToplLeft.X
Bezier.origin.Y = ToplLeft.Y + R
Bezier.control1.X = ToplLeft.X
Bezier.control1.Y = ToplLeft.Y + R * (1-MagicConst)
Bezier.control2.X = ToplLeft.X + R * (1-MagicConst)
Bezier.control2.Y = ToplLeft.Y
Bezier.destination.X = ToplLeft.X + R
Bezier.destination.Y = ToplLeft.Y

about MagicConstant

您可以轻松找到其他角落的类似对称坐标。 我没有考虑极短矩形边(< 2 * R)

的情况