Getting and setting the RGB / RGBA value of a pixel in a CCSprite (cocos2d-x)

孤者浪人 提交于 2019-11-30 09:59:18

Here is my solution for you :

1.First make a CCImage version of your image:

I) from File :

CCImage *img=  new CCImage();
img->initWithImageFile("colors.png");

II) From Sprite :

  • II.1) CCSprite -> RenderTexture2D

  • II.2) RenderTexture2D -> CCImage (CCImage *testImage = RenderText2D->newCCImage();)

2.Then You can do what you need :

    CCImage *img= ... // make CCImage from CCSprite
    int x=3;
    if(img->hasAlpha())
        x=4;

    unsigned char *data = new unsigned char[img->getDataLen()*x];   
    data = img->getData();
    // [0][0] => Left-Top Pixel !
    // But cocos2d Location Y-axis is Bottom(0) to Top(max)

    for(int i=0;i<img->getWidth();i++)
    {
        for(int j=0;j<img->getHeight();j++)
        {
            unsigned char *pixel = data + (i + j * img->getWidth()) * x;

           // You can see/change pixels' RGBA value(0-255) here !
            unsigned char r = *pixel;
            unsigned char g = *(pixel + 1);
            unsigned char b = *(pixel + 2) ;
            unsigned char a = *(pixel + 3);
        }
    }

3.Then, convert it to texture_2D

//CCImage -> Texture2d
    texture_2D= new CCTexture2D();
    texture_2D->initWithImage(img);

4.And Finally back to CCSprite

CCSprite *result=  CCSprite::createWithTexture(texture_2D);
irwinb

This can be done a couple of ways. What I have done in the past is to just called setColor on the sprite to some color close to what you are looking for. That had worked for my purposes.

my_sprite.setColor( ccc3( 128, 128, 128 ) );

Another solution (more thorough and precise): how to implement grayscale rendering in OpenGL?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!