UIImage黑白透明。

时间:2013-08-02 05:42:54

标签: iphone ipad

以下是将图像转换为黑白图像的代码。除非带有透明度的图像出现,否则它工作正常。该透明区域转换为黑色。请帮忙解决这里有什么问题。

+ (UIImage *)getBlackAndWhiteVersionOfImage:(UIImage *)anImage
{
    UIImage *newImage;
    UIImage *imageToDisplay;

    int orientation = anImage.imageOrientation;

    if (anImage) {
        CGColorSpaceRef colorSapce = CGColorSpaceCreateDeviceGray();
        CGContextRef context = CGBitmapContextCreate(nil, anImage.size.width * anImage.scale, anImage.size.height * anImage.scale, 8, anImage.size.width * anImage.scale, colorSapce, kCGImageAlphaNone);
        CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
        CGContextSetShouldAntialias(context, NO);
        CGContextDrawImage(context, CGRectMake(0, 0, anImage.size.width, anImage.size.height), [anImage CGImage]);

        CGImageRef bwImage = CGBitmapContextCreateImage(context);
        CGContextRelease(context);
        CGColorSpaceRelease(colorSapce);

        UIImage *resultImage = [UIImage imageWithCGImage:bwImage];
        CGImageRelease(bwImage);

        UIGraphicsBeginImageContextWithOptions(anImage.size, NO, anImage.scale);
        [resultImage drawInRect:CGRectMake(0.0, 0.0, anImage.size.width, anImage.size.height)];
        newImage = UIGraphicsGetImageFromCurrentImageContext();
         imageToDisplay =
        [UIImage imageWithCGImage:[newImage CGImage]
                            scale:1.0
                      orientation: orientation];

        UIGraphicsEndImageContext();
    }

    return imageToDisplay;
}

1 个答案:

答案 0 :(得分:1)

我不认为灰色空间有一个alpha组件