ios - 从 UIImage 中移除 alpha channel

标签 ios uiimageview uiimage alpha cgcontext

我使用以下方法从文件系统中获取解压后的 uiimage。然而,当我打开颜色混合层时,UIImageView 被着色为红色,即使 UIImageView 设置为不透明。

文件系统上的图像没有 alpha channel 。我尝试设置 CGContextSetAlpha(bitmapContext, 1),但仍然有混合层。

有人知道如何在使用 CGContextDrawImage 时删除 alpha channel 吗?

- (UIImage *)decompressedImage
{
    CGImageRef imageRef = self.CGImage;
    CGRect rect = CGRectMake(0.f, 0.f, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
    CGContextRef bitmapContext = CGBitmapContextCreate(NULL,
                                                       rect.size.width,
                                                       rect.size.height,
                                                       CGImageGetBitsPerComponent(imageRef),
                                                       CGImageGetBytesPerRow(imageRef),
                                                       CGImageGetColorSpace(imageRef),
                                                       kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little
                                                       );
    // kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little are the bit flags required
    //  so that the main thread doesn't have any conversions to do.

    CGContextDrawImage(bitmapContext, rect, imageRef);

    CGImageRef decompressedImageRef = CGBitmapContextCreateImage(bitmapContext);
    UIImage* decompressedImage = [UIImage imageWithCGImage:decompressedImageRef
                                                     scale:[[UIScreen mainScreen] scale]
                                               orientation:UIImageOrientationUp];
    CGImageRelease(decompressedImageRef);
    CGContextRelease(bitmapContext);

    return decompressedImage;
}

最佳答案

在上下文的选项中,尝试选项

kCGImageAlphaNoneSkipLast

kCGImageAlphaNoneSkipFirst

取决于您使用的是 RGBA 还是 ARGB

即,

CGContextRef bitmapContext = CGBitmapContextCreate(NULL,
                                                       rect.size.width,
                                                       rect.size.height,
                                                       CGImageGetBitsPerComponent(imageRef),
                                                       CGImageGetBytesPerRow(imageRef),
                                                       CGImageGetColorSpace(imageRef),
                                                       kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Little
                                                       );

关于ios - 从 UIImage 中移除 alpha channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21416358/

相关文章:

ios - 从给定的 UIImage 创建有色 UIImage

ios - 使用图像动态调整表格 View 单元格的大小

ios - 获取嵌套在 UIScrollView 中的 UIImageView 中两个 CGPoint 之间的距离

ios - 无法获取 UIImage 的 init(contentsOfFile :) to work

objective-c - 为什么图像不显示在 UIImageView 中?

ios - 委托(delegate)意外变更

objective-c - 找不到数据库文件

ios:图像有时无法从包中加载

ios - 以像素为单位的 UIImage 大小

ios - CMVideoFormatDescriptionGetCleanAperture() 快速错误