Tinting a grayscale NSImage (or CIImage)

后端 未结 8 1996
轮回少年
轮回少年 2021-01-30 09:02

I have a grayscale image which I want to use for drawing Cocoa controls. The image has various levels of gray. Where it is darkest, I want it to draw a specified tint color dark

8条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-30 09:41

    I wanted to tint an image with a tint color that had alpha without seeing the original colors of the image show through. Here's how you can do that:

    extension NSImage {
        func tinting(with tintColor: NSColor) -> NSImage {
            guard let cgImage = self.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return self }
    
            return NSImage(size: size, flipped: false) { bounds in
                guard let context = NSGraphicsContext.current?.cgContext else { return false }
    
                tintColor.set()
                context.clip(to: bounds, mask: cgImage)
                context.fill(bounds)
    
                return true
            }
        }
    }
    

提交回复
热议问题