gpt4 book ai didi

swift - 将 SVG 节点 (Macaw) 转换为 NSImage Swift4/Cocoa

转载 作者:行者123 更新时间:2023-11-28 05:51:40 27 4
gpt4 key购买 nike

我正在尝试将 Macaw SVG(节点)转换为 NSImage。我能够在 Macaw 论坛上找到 IOS 的示例代码,但无法使其在 Cocoa 中运行。

Macaw 库中有对所有缺失函数(UIGraphicsBeginImageContext 等)的引用,如 MGraphicsBeginImageContext 但尚未能够访问它们(使用未解析的标识符“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 }
}

关于swift - 将 SVG 节点 (Macaw) 转换为 NSImage Swift4/Cocoa,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52725255/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com