Tom*_*mmy 41

要扩展quixoto的答案,因为我有自己的项目的相关源代码,如果你需要放弃CPU上的像素操作,那么我已经添加了以下内容,应该可以解决这个问题:

@implementation UIImage (NegativeImage)

- (UIImage *)negativeImage
{
    // get width and height as integers, since we'll be using them as
    // array subscripts, etc, and this'll save a whole lot of casting
    CGSize size = self.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), [self 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++)
        {
            // get RGB values. We're dealing with premultiplied alpha
            // here, so we need to divide by the alpha channel (if it
            // isn't zero, of course) to get uninflected RGB. We
            // multiply by 255 to keep precision while still using
            // integers
            int r, g, b; 
            if(linePointer[3])
            {
                r = linePointer[0] * 255 / linePointer[3];
                g = linePointer[1] * 255 / linePointer[3];
                b = linePointer[2] * 255 / linePointer[3];
            }
            else
                r = g = b = 0;

            // perform the colour inversion
            r = 255 - r;
            g = 255 - g;
            b = 255 - b;

            // multiply by alpha again, divide by 255 to undo the
            // scaling before, store the new values and advance
            // the pointer we're reading pixel data from
            linePointer[0] = r * linePointer[3] / 255;
            linePointer[1] = g * linePointer[3] / 255;
            linePointer[2] = b * linePointer[3] / 255;
            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);

    // and return
    return returnImage;
}

@end
Run Code Online (Sandbox Code Playgroud)

这样就为UIImage添加了一个类别方法:

  1. 创建一个清晰的CoreGraphics位图上下文,它可以访问内存
  2. 绘制UIImage
  3. 遍历每个像素,从预乘的alpha转换为未反射的RGB,分别反转每个通道,再次乘以alpha并存储回来
  4. 从上下文中获取图像并将其包装到UIImage中
  5. 自己清理后,返回UIImage

  • 要使此代码准备好Retina,请使用:`int width = size.width*self.scale; int height = size.height*self.scale;` (11认同)
  • @VincentTourraine并用`[UIImage imageWithCGImage:cgImage scale:self.scale orientation:UIImageOrientationUp]替换`UIImage*returnImage = [UIImage imageWithCGImage:cgImage]` (3认同)

小智 23

使用CoreImage:

#import <CoreImage/CoreImage.h>

@implementation UIImage (ColorInverse)

+ (UIImage *)inverseColor:(UIImage *)image {
    CIImage *coreImage = [CIImage imageWithCGImage:image.CGImage];
    CIFilter *filter = [CIFilter filterWithName:@"CIColorInvert"];
    [filter setValue:coreImage forKey:kCIInputImageKey];
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    return [UIImage imageWithCIImage:result];
}

@end
Run Code Online (Sandbox Code Playgroud)

  • 最后一行会更好:[UIImage imageWithCIImage:result scale:image.scale orientation:image.imageOrientation]; 以便保留原始图像的比例和方向. (3认同)

MLB*_*BDG 6

Swift 3 更新:( 来自@BadPirate 答案)

extension UIImage {
func inverseImage(cgResult: Bool) -> UIImage? {
    let coreImage = UIKit.CIImage(image: self)
    guard let filter = CIFilter(name: "CIColorInvert") else { return nil }
    filter.setValue(coreImage, forKey: kCIInputImageKey)
    guard let result = filter.value(forKey: kCIOutputImageKey) as? UIKit.CIImage else { return nil }
    if cgResult { // I've found that UIImage's that are based on CIImages don't work with a lot of calls properly
        return UIImage(cgImage: CIContext(options: nil).createCGImage(result, from: result.extent)!)
    }
    return UIImage(ciImage: result)
  }
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*tto 5

当然,这是可能的——一种方法是使用“差异”混合模式 ( kCGBlendModeDifference)。有关设置图像处理的代码概要,请参阅此问题(以及其他问题)。使用您的图像作为底部(基础)图像,然后在其顶部绘制纯白色位图。

您还可以手动执行逐像素操作,方法是获取CGImageRef并将其绘制到位图上下文中,然后循环位图上下文中的像素。


Bad*_*ate 5

创建了一个快速扩展来做到这一点。另外,由于基于 CIImage 的 UIImage 崩溃了(大多数库假设 CGImage 已设置),我添加了一个选项来返回基于修改后的 CIImage 的 UIImage:

extension UIImage {
    func inverseImage(cgResult: Bool) -> UIImage? {
        let coreImage = UIKit.CIImage(image: self)
        guard let filter = CIFilter(name: "CIColorInvert") else { return nil }
        filter.setValue(coreImage, forKey: kCIInputImageKey)
        guard let result = filter.valueForKey(kCIOutputImageKey) as? UIKit.CIImage else { return nil }
        if cgResult { // I've found that UIImage's that are based on CIImages don't work with a lot of calls properly
            return UIImage(CGImage: CIContext(options: nil).createCGImage(result, fromRect: result.extent))
        }
        return UIImage(CIImage: result)
    }
}
Run Code Online (Sandbox Code Playgroud)