Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SVG Node (Macaw) to NSImage Swift4 / Cocoa

Tags:

macos

swift

svg

I'm trying to convert from a Macaw SVG (Node) into an NSImage. I was able to find sample code for IOS on the Macaw forum but not able to make it work in Cocoa.

There are references in the Macaw libraries for all the missing functions (UIGraphicsBeginImageContext, etc) as MGraphicsBeginImageContext but have not been able to access them yet (Use of unresolved identifier 'UIGraphicsBeginImageContext')

Here's the sample code from the original article 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()
        }
    }
like image 531
Jc Nolan Avatar asked Oct 20 '25 18:10

Jc Nolan


1 Answers

Here is tweaked code provided by the makers of Macaw which seems to solve the problem. I needed to add an inverter as the image was drawing upside down and their original suggestion of NSGraphicsContext.current?.graphicsPort did not seem stable/reliable and I ended up using NSGraphicsContext.current?.cgContext instead:

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 }
}
like image 149
Jc Nolan Avatar answered Oct 23 '25 09:10

Jc Nolan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!