0

我有一个带有一些 alpha 值的 UIImage 并且想要制作它的灰色版本。我一直在使用以下内容,它适用于图像的非 alpha 部分,但是由于不支持/关闭 alpha 部分,所以 alpha 部分变成黑色......我将如何成功打开 alpha 支持?

(我从stackoverflow周围的代码修改了这个,以支持其他比例(阅读视网膜))

-(UIImage*)grayscaledVersion2 {
    // Create image rectangle with current image width/height
    const CGRect RECT = CGRectMake(0, 0, self.size.width * self.scale, self.size.height * self.scale);

    // Grayscale color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

    // Create bitmap content with current image size and grayscale colorspace
    CGContextRef context = CGBitmapContextCreate(nil, RECT.size.width, RECT.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
    // kCGImageAlphaNone = no alpha, kCGImageAlphaPremultipliedFirst/kCGImageAlphaFirst/kCGImageAlphaLast = crash

    // Draw image into current context, with specified rectangle
    // using previously defined context (with grayscale colorspace)
    CGContextDrawImage(context, RECT, [self CGImage]);

    // Create bitmap image info from pixel data in current context
    CGImageRef imageRef = CGBitmapContextCreateImage(context);

    UIImage* imageGray = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
    DLog(@"greyed %@ (%f, %f %f) into %@ (%f, %f %f)", self, self.scale, self.size.width, self.size.height, imageGray, imageGray.scale, imageGray.size.width, imageGray.size.height);

    // Release colorspace, context and bitmap information
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);

    return imageGray;
}
4

0 回答 0