cocos2d-xcocos2d-x-3.0cocos2d-x-3.x

How to create a white square as a sprite, without having to load an image file?


Normally we either create a sprite from a sprite frame, a file, or a texture by doing something like:

Sprite* foo =  Sprite::create(filename);

How can one create a white square of specified dimensions without using DrawNode or passing a file to a sprite ?

I know this is possible, because I stumbled upon another post which described how to do it, but neglected to book mark it, and the post doesn't show up in search results..


Solution

  • Something like this:

    auto dataLen = width * height * bitsPerPixel * sizeof(unsigned char);
    auto data = static_cast<unsigned char*>(malloc(dataLen));
    memset(data, 255, dataLen);
    auto texture = new Texture2D();
    texture->initWithData(data, dataLen, Texture2D::PixelFormat::RGBA8888, width, height, Size(width, height));
    auto sprite = Sprite::createWithTexture(texture);