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

Why do I need it?

Basically I need to turn a color image into gray. Turning on the gray version of the image may be a solution, but there is no place in my situation - I do not want my APK to be too large. In addition, I would like to work with pixels for some effects. Again, this should make the APK smaller.

I found getPixel setPixel from CCTexture2D and Getting an RGBA Image Pixel , but I would like to do something simpler.

Any help is appreciated.

Thanks!

+6
source share
2 answers

Here is my solution for you:

1. First create a version of your CCImage image:

I) from file:

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

II) From the 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. Finally return to CCSprite

 CCSprite *result= CCSprite::createWithTexture(texture_2D); 
+7
source

There are several ways to do this. What I have done in the past is simply to name setColor on the sprite with some color close to what you are looking for. This worked for my purposes.

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

Another solution (more complete and accurate): how to implement grayscale rendering in OpenGL?

0
source

Source: https://habr.com/ru/post/910486/


All Articles