在 Cocos2dx 中绘制矩形

Drawing Rectangle in Cocos2dx

本文关键字:绘制 Cocos2dx      更新时间:2023-10-16

我在iOS环境中使用Cocos2dx库绘制基本白色矩形时遇到问题。我已经查看了其他几个实现作为指导。

http://discuss.cocos2d-x.org/t/draw-rectangle-with-drawrect-in-cocos2dx-not-working/14836/3

Cocos2d-x: 如何绘制调整大小的矩形?

基本上看起来我需要使用 DrawNode::

create() 的类方法来制作节点,然后像在 openGL 中一样建立顶点,然后使用 DrawNode->drawPolygon 方法绘制它,并使用 cocos2d::Layer 子类的 addChild 方法将子节点添加到场景中。

这是我的代码。

bool JFScene::init()
{
    if ( !Layer::init() )
    {
        return false;
    }
    auto visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    auto closeItem = MenuItemImage::create(
                                       "CloseNormal.png",
                                       "CloseSelected.png",
                                           CC_CALLBACK_1(JFScene::menuCloseCallback, this));

    closeItem->setScale(2.0);
    closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
                            origin.y + closeItem->getContentSize().height/2));

    auto menu = Menu::create(closeItem, NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu, 1);
    auto CButton = Sprite::create("CButton.png");
    CButton->setPosition(
    Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y)
);
    this->addChild(CButton, 1);

    auto rectNode = DrawNode::create();
    Vec2 vertices[4] = {
        Vec2(-50, -50),
        Vec2(50, -50),
        Vec2(50, 50),
        Vec2(-50, 50)
    };
    rectNode->drawPolygon(vertices, 4, Color4F::WHITE, 1, Color4F::WHITE);
    this->addChild(rectNode);
    return true;
 }

奇怪的是,当我在iPhone 5s上运行CButton节点以及默认文件中包含的关闭项时,它似乎呈现了,但是我尝试绘制的白色矩形没有渲染。知道为什么吗?

你想画一个矩形...看看这个代码片段:

auto rectNode = DrawNode::create();
Vec2 rectangle[4];
rectangle[0] = Vec2(-50, -50);
rectangle[1] = Vec2(50, -50);
rectangle[2] = Vec2(50, 50);
rectangle[3] = Vec2(-50, 50);
Color4F white(1, 1, 1, 1);
rectNode->drawPolygon(rectangle, 4, white, 1, white);
this->addChild(rectNode);

我希望它对你有用。

参考:cocso2d-x 论坛


此外,如果您没有,我建议您看看这个类似的问题。