Swift 如何将NSImage绘制到CGContext

Swift 如何将NSImage绘制到CGContext,swift,macos,Swift,Macos,我有一个对象NSImage,我想将其绘制到CGContext。 我发现CGContext没有相应的方法,但似乎有一种CGImage方法,clip func clip(to: CGRect, mask: CGImage) 请问我需要怎么做?最简单的方法是创建一个NSGraphicsContext包装您的CGContext,并将其纳入其中: let gc: CGContext = ... let nsImage: NSImage = ... let rect: CGRect = ... let

我有一个对象NSImage,我想将其绘制到CGContext。 我发现CGContext没有相应的方法,但似乎有一种CGImage方法,clip

func clip(to: CGRect, mask: CGImage)

请问我需要怎么做?

最简单的方法是创建一个
NSGraphicsContext
包装您的
CGContext
,并将其纳入其中:

let gc: CGContext = ...
let nsImage: NSImage = ...
let rect: CGRect = ...

let priorNsgc = NSGraphicsContext.current
defer { NSGraphicsContext.current = priorNsgc }
NSGraphicsContext.current = NSGraphicsContext(cgContext: gc, flipped: false)
nsImage.draw(in: rect)

将NSImge对象转换为CIImage对象。然后可以使用它创建一个CGContext。