【问题标题】:how do Sprite make trim programmatically in cocos2dx?Sprite 如何在 cocos2dx 中以编程方式进行修剪?
【发布时间】:2020-11-27 02:43:55
【问题描述】:

图像可以是透明像素。 如何在没有透明像素的情况下获得适合此图像的矩形的最小尺寸? 我想得到这样的东西:

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

也许你不会给我答案,但至少是一些提示。我会很感激你的。

【问题讨论】:

    标签: cocos2d-x


    【解决方案1】:

    这只是一个基本示例。您必须对其进行自定义。

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

    然后您遍历图像中的每个像素并确定图像边界处的哪些像素是不透明的,并使用它来计算一个矩形。

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

    在“完成自己”部分,您只需跟踪第一个/最后一个不透明像素的边界。 您需要四个变量,每边一个。

    在循环结束时,您只需使用四个点作为矩形的边创建一个矩形!

    如果这解决了您的问题,请将其标记为正确。

    【讨论】:

      猜你喜欢
      • 2010-10-07
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多