我正试图从Macaw SVG(节点)转换为NSImage。我在Macaw论坛上找到了IOS的示例代码,但无法在Cocoa中运行。
Macaw库中有作为MGraphicsBeginImageContext的所有缺少函数(UIGraphicsBeginImageContext等)的引用,但尚未能够访问它们(使用未解析的标识符UIGraphicsBeginImageContext)
这是原始文章的示例代码https://github.com/exyte/Macaw/pull/382#issuecomment-393422770

func svgToImge(resourceName: String, size: CGSize) -> NSImage {
        if let rootNode = try? SVGParser.parse(path: resourceName)
        {
            let macawView = MacawView(node: rootNode, frame:CGRect(origin: CGPoint.zero, size: size))
            UIGraphicsBeginImageContext(size)
            macawView.layer.render(in: UIGraphicsGetCurrentContext()!)
            let img =  UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return img!
        } else {
            return NSImage()
        }
    }

最佳答案

以下是Macaw制造商提供的经过修改的代码,似乎可以解决这个问题。我需要添加一个逆变器,因为图像是颠倒的,他们原来的建议NSGraphicsContext.current?.graphicsPort看起来不稳定/不可靠,我最终使用了NSGraphicsContext.current?.cgContext代替:

func svgToNSImage(resourcePath: String, size: CGSize) -> NSImage? {

   if let rootNode = try? SVGParser.parse(path: resourcePath) {

        let macawView = MacawView(node: rootNode, frame: CGRect(origin: CGPoint.zero, size: size))
        macawView.wantsLayer = true

        let image = NSImage(size: macawView.bounds.size)
        image.lockFocus()

        //        if let ctx = NSGraphicsContext.current?.graphicsPort {
        if let ctx = NSGraphicsContext.current?.cgContext {
            // image is drawing upside down, invert it and render
            ctx.translateBy(x: 0, y: size.height)
            ctx.scaleBy(x: 1.0, y: -1.0)
            macawView.layer?.render(in: ctx)
        }
        image.unlockFocus()
        return image

    } else { return nil }
}

10-01 15:06