how do Sprite make trim programmatically in cocos2dx?

The image can be with transparent pixels. How do I get the minimum size of a rectangle that fits this image without transparent pixels? I want to get something like this:

cocos2d::Rect getBoundingBoxTrim(cocos2d::Sprite* sprite);

Perhaps you will not give me an answer, but at least some tips. I will be very grateful to you.

Upvotes: 0

Views: 82

Answers (1)

Rahul Iyer
Rahul Iyer

Reputation: 21025

This is just a basic example. You will have to customize it.

Image* img = new Image();
img->initWithImageFile("my file.png");

Then you iterate over each pixel in the image and determine which pixels at the boundary of the image are opaque, and use that to compute a rectangle.

int leftMost;
int rightMost;
int upperMost;
int lowerMost;

unsigned char *data = new unsigned char[img->getDataLen()*x];   
    data = img->getData();

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);

            if (a>0){
            // this pixel is opaque. You can use a different threshold for transparency besides 0, depending on how transparent you won't to consider as "transparent".
                 

                     //Complete yourself: 
                if(i<leftMost){
                     leftMost = i;
                }
                if(i> rightMost){
                    rightMost = i;
                }
                if(j> upperMost){
                    upperMost = j;
                }
                if(j< lowerMost){
                    lowerMost = j;
                }
                }
            }
        }

In the "Complete yourself" section, you just keep track of the boundary of where the first / last opaque pixel is. You need four variables, one for each side.

At the end of the loop, you simply create a rectangle using the four points as sides of the rectangle!

If this solves your problem, mark it as correct.

Upvotes: 2

Related Questions