Build Codecov Platforms Swift 5.1 License Mastodon

简介

SVGPath 是一个开源的 SVG 路径语法解析器,可以轻松地从这种流行的格式创建 CGPath

SVGPath 可以在所有 Apple 平台以及 Linux 上运行(尽管 Linux 不支持 CoreGraphics API,因此如果您需要绘制路径,则需要提供自己的实现)。

安装

SVGPath 打包为动态框架,您可以将其导入到您的 Xcode 项目中。您可以通过手动方式安装,也可以使用 Swift Package Manager 安装。

注意: SVGPath 需要 Xcode 10+ 才能构建,并且在 iOS 10+ 或 macOS 10.12+ 上运行。

要使用 Swift Package Manager 安装,请将以下内容添加到您的 Package.swift 文件中的 dependencies: 部分

.package(url: "https://github.com/nicklockwood/SVGPath.git", .upToNextMinor(from: "1.0.0")),

用法

您可以按如下方式创建 SVGPath 的实例

let svgPath = try SVGPath(string: "M150 0 L75 200 L225 200 Z")

请注意,SVGPath 构造函数是一个抛出函数。如果提供的字符串无效或格式错误,它将抛出一个 SVGError

一旦您创建了一个 SVGPath 对象,在大多数情况下,您会希望将其转换为 CGPath 以便在 Apple 平台上渲染。为此,您可以使用

let cgPath = CGPath.from(svgPath: svgPath)

作为快捷方式,您可以直接从 SVG 路径字符串创建 CGPath

let cgPath = try CGPath.from(svgPath: "M150 0 L75 200 L225 200 Z")

一旦您拥有了 CGPath,您就可以使用 CoreGraphics 上下文或 CAShapeLayer 在 iOS 或 macOS 上渲染它。

高级用法

您可以使用 init(cgPath:) 初始化器将 CGPath 转换为 SVGPath

let rect = CGRect(x: 0, y: 0, width: 10, height: 10)
let cgPath = CGPath(rect: rect, transform: nil)
let svgPath = SVGPath(cgPath: cgPath)

要将 SVGPath 转换回 String,请使用 string(with:) 方法。这对于将 CGPath 导出为 SVG 字符串非常有用

let svgPath = SVGPath(cgPath: ...)
let options = SVGPath.WriteOptions(prettyPrinted: true, wrapWidth: 80)
let string = svgPath.string(with: options)

也可以在不使用 CoreGraphics 的情况下使用 SVGPath。您可以使用 commands 属性迭代原始路径组件

for command in svgPath.commands {
    switch command {
    case .moveTo(let point):
        ...
    case .lineTo(let point):
        ...
    default:
        ...   
    }   
}

或者,您可以使用 points()getPoints() 方法,以您偏好的细节级别将整个路径转换为扁平的点数组。

这些可以用于使用您选择的任何图形 API,通过简单的直线段渲染路径

let detail = 10 // number of sample points used to represent curved segments
let points = svgPath.points(withDetail: detail)

注意: 坐标在内部以反转的 Y 坐标存储,以匹配 macOS/iOS 上 Core Graphics 使用的坐标系。

致谢

SVGPath 库主要由 Nick Lockwood 完成。

完整贡献者列表