ccColor3B from string

I recently required a method to convert a string into a ccColor3B struct, similar to CCSizeFromString()

So I edited CCNS.cpp to include the method:

ccColor3B CCColor3BFromString(const char* pszContent)
{
    ccColor3B ret = {0,0,0};

    do
    {
        strArray strs;
        CC_BREAK_IF(!splitWithForm(pszContent, strs));

        ret.r = (GLubyte) atof(strs[0].c_str());
        ret.g = (GLubyte) atof(strs[1].c_str());
        ret.b = (GLubyte) atof(strs[2].c_str());

    } while (0);

    return ret;
}

and in splitWithForm() method changed this piece of code:

if (strs.size() != 2 || strs[0].length() == 0 || strs[1].length() == 0)
    {
        if (strs.size() != 3 || strs[0].length() == 0 || strs[1].length() == 0 || strs[2].length() == 0)
        {
            strs.clear();
            break;
        }
    }
}

also added in CCNS.h

ccColor3B CC_DLL CCColor3BFromString(const char* pszContent);

and then its easy to load color values from a string:

ccColor3B color = CCColor3BFromString("{16,123,255}");

Perhaps this can be added for all colour structs in a future release?

1 Like