Tinting a grayscale NSImage (or CIImage)

后端 未结 8 1932
轮回少年
轮回少年 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:53

    Swift 5 version that also handles the alpha component of the tint color.

    I use this to support dark mode with multiple icon states by converting template icons to different colors and transparency levels. For example, you could pass NSColor(white: 0, alpha: 0.5) to get a dimmed version of an icon for light mode, and NSColor(white: 1, alpha: 0.5) to get a dimmed version for dark mode.

    func tintedImage(_ image: NSImage, color: NSColor) -> NSImage {
        let newImage = NSImage(size: image.size)
        newImage.lockFocus()
    
        // Draw with specified transparency
        let imageRect = NSRect(origin: .zero, size: image.size)
        image.draw(in: imageRect, from: imageRect, operation: .sourceOver, fraction: color.alphaComponent)
    
        // Tint with color
        color.withAlphaComponent(1).set()
        imageRect.fill(using: .sourceAtop)
    
        newImage.unlockFocus()
        return newImage
    }
    

提交回复
热议问题