绘制标准NSImage倒置(白色而不是黑色)

时间:2010-01-26 06:03:54

标签: objective-c macos drawing nsimage invert

我正在尝试用白色而不是黑色绘制标准NSImage。以下工作正常适用于在当前NSGraphicsContext中以黑色绘制图像:

NSImage* image = [NSImage imageNamed:NSImageNameEnterFullScreenTemplate];
[image drawInRect:r fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];

我期待NSCompositeXOR能够做到这一点,但没有。我是否需要沿着复杂的[CIFilter filterWithName:@“CIColorInvert”]路径走下去?我觉得我必须遗漏一些简单的东西。

的Anders

3 个答案:

答案 0 :(得分:6)

Core Image路线将是最可靠的。它实际上并不复杂,我在下面发布了一个示例。如果您知道不会翻转任何图像,则可以删除转换代码。需要注意的主要事项是,从NSImageCIImage的转换在性能方面可能很昂贵,因此您应该确保在可能的情况下缓存CIImage并且不要重新在每次绘图操作中创建它。

CIImage* ciImage = [[CIImage alloc] initWithData:[yourImage TIFFRepresentation]];
if ([yourImage isFlipped])
{
    CGRect cgRect    = [ciImage extent];
    CGAffineTransform transform;
    transform = CGAffineTransformMakeTranslation(0.0,cgRect.size.height);
    transform = CGAffineTransformScale(transform, 1.0, -1.0);
    ciImage   = [ciImage imageByApplyingTransform:transform];
}
CIFilter* filter = [CIFilter filterWithName:@"CIColorInvert"];
[filter setDefaults];
[filter setValue:ciImage forKey:@"inputImage"];
CIImage* output = [filter valueForKey:@"outputImage"];
[output drawAtPoint:NSZeroPoint fromRect:NSRectFromCGRect([output extent]) operation:NSCompositeSourceOver fraction:1.0];

注意:释放/保留内存管理留作练习,上面的代码假设垃圾收集。

如果要以任意大小渲染图像,可以执行以下操作:

NSSize imageSize = NSMakeSize(1024,768); //or whatever size you want
[yourImage setSize:imageSize];
[yourImage lockFocus];
NSBitmapImageRep* bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, imageSize.width, imageSize.height)];
[yourImage unlockFocus];
CIImage* image = [CIImage imageWithData:[bitmap TIFFRepresentation]];

答案 1 :(得分:1)

这是一个使用Swift 5.1的解决方案,多少基于上述解决方案。请注意,我没有缓存图像,所以它可能不是最有效的,因为我的主要用例是根据当前的配色方案是浅色还是深色来翻转工具栏按钮中的小单色图像。

import os
import AppKit
import Foundation

public extension NSImage {

    func inverted() -> NSImage {
        guard let cgImage = self.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
            os_log(.error, "Could not create CGImage from NSImage")
            return self
        }

        let ciImage = CIImage(cgImage: cgImage)
        guard let filter = CIFilter(name: "CIColorInvert") else {
            os_log(.error, "Could not create CIColorInvert filter")
            return self
        }

        filter.setValue(ciImage, forKey: kCIInputImageKey)
        guard let outputImage = filter.outputImage else {
            os_log(.error, "Could not obtain output CIImage from filter")
            return self
        }

        guard let outputCgImage = outputImage.toCGImage() else {
            os_log(.error, "Could not create CGImage from CIImage")
            return self
        }

        return NSImage(cgImage: outputCgImage, size: self.size)
    }
}

fileprivate extension CIImage {
    func toCGImage() -> CGImage? {
        let context = CIContext(options: nil)
        if let cgImage = context.createCGImage(self, from: self.extent) {
            return cgImage
        }
        return nil
    }
}

答案 2 :(得分:0)

只需注意一点:我发现CIColorInvert过滤器并不总是可靠的。例如,如果要反转在Photoshop中反转的图像,CIFilter将生成更亮的图像。据我所知,这是因为CIFilter的伽玛值(伽玛是1)和来自其他来源的图像的差异。

当我在寻找改变CIFilter的伽玛值的方法时,我发现CIContext中存在一个错误:从默认值1改变其伽玛值会产生不可预测的结果。

无论如何,还有另一种解决方案可以通过反转NSBitmapImageRep的像素来反转NSImage,它总能产生正确的结果。

我正在重新发布etutorials.org(http://bit.ly/Y6GpLn)中的代码:

// srcImageRep is the NSBitmapImageRep of the source image
int n = [srcImageRep bitsPerPixel] / 8;           // Bytes per pixel
int w = [srcImageRep pixelsWide];
int h = [srcImageRep pixelsHigh];
int rowBytes = [srcImageRep bytesPerRow];
int i;

NSImage *destImage = [[NSImage alloc] initWithSize:NSMakeSize(w, h)];
NSBitmapImageRep *destImageRep = [[[NSBitmapImageRep alloc] 
      initWithBitmapDataPlanes:NULL
          pixelsWide:w
          pixelsHigh:h
          bitsPerSample:8
          samplesPerPixel:n
          hasAlpha:[srcImageRep hasAlpha] 
          isPlanar:NO
          colorSpaceName:[srcImageRep colorSpaceName]
          bytesPerRow:rowBytes 
          bitsPerPixel:NULL] autorelease];

unsigned char *srcData = [srcImageRep bitmapData];
unsigned char *destData = [destImageRep bitmapData];

for ( i = 0; i < rowBytes * h; i++ )
    *(destData + i) = 255 - *(srcData + i);

[destImage addRepresentation:destImageRep];