核心图形反转alpha

时间:2014-03-28 10:53:09

标签: ios cocos2d-iphone core-graphics mask

目前我在Cocos2D中遇到CCClippingNode问题,并按照here的规定进行转换。现在Viktor(SpriteBuilder的作者)gave a tip,我可以使用Core Graphics屏蔽图像。

我现在正在做什么,它的确有效。然而,Core Graphics使用与屏蔽完全相反的alpha作为Cocos2d。是否有可能在运行中反转UIImage(灰度)的alpha值?

如果我想用Cocos掩盖图像中的圆圈,我需要这个遮罩。

Cocos Mask

但它必须是核心图形中的。

Core Graphics

是否可以动态地从顶部图像创建底部图像? (例如将其反转为alpha)

2 个答案:

答案 0 :(得分:0)

How to convert UIImage/CGImageRef's alpha channel to mask?

Ben对该链接问题的回答解决了给定UIImage的反转alpha。只需删除/评论代码的以下部分

for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
    unsigned char val = alphaData[y*strideLength + x];
    val = 255 - val;
    alphaData[y*strideLength + x] = val;
}

PS:无法添加评论。

答案 1 :(得分:0)

我根据这个答案得到答案honors for @Tommy

CGSize size = finalImage.size;
    int width = size.width;
    int height = size.height;
    // Create a suitable RGB+alpha bitmap context in BGRA colour space
    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *memoryPool = (unsigned char *)calloc(width*height*4, 1);
    CGContextRef context = CGBitmapContextCreate(memoryPool, width, height, 8, width * 4, colourSpace, kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colourSpace);

    // draw the current image to the newly created context
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), [finalImage CGImage]);

    // run through every pixel, a scan line at a time...
    for(int y = 0; y < height; y++)
    {
        // get a pointer to the start of this scan line
        unsigned char *linePointer = &memoryPool[y * width * 4];

        // step through the pixels one by one...
        for(int x = 0; x < width; x++)
        {

            if(linePointer[3]){
                linePointer[3]=255-linePointer[3];
            }
            linePointer += 4;
        }
    }

    // get a CG image from the context, wrap that into a
    // UIImage
    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    UIImage *returnImage = [UIImage imageWithCGImage:cgImage];

    // clean up
    CGImageRelease(cgImage);
    CGContextRelease(context);
    free(memoryPool);

    //use returnImage as you want