CGPathIntersection

CGPathIntersection 是一个用于 iOS、macOS 和 tvOS 的库,用于识别两个 CGPath 相交的点。

令人惊讶的是,CoreGraphics 没有开箱即用地提供此功能。对于简单的几何形状(尤其是直线),可以进行解析计算相交点,但是当考虑到 CGPath 可以是任意复杂时,这种方法就变得相当具有挑战性。CGPathIntersection 通过将每个路径渲染成图像,然后找到它们相交的确切像素来解决此问题。

安装

Swift Package Manager

将以下依赖项添加到您的包定义中

.package(
  name: "CGPathIntersection",
  url: "https://github.com/calda/CGPathIntersection.git",
  from: "4.0.0")

Carthage

github "calda/CGPathIntersection" 添加到您的 Cartfile

CocoaPods

pod 'CGPathIntersection' 添加到您的 Podfile

用法

import CGPathIntersection

let path1 = CGPath(...)
let path2 = CGPath(...)
        
path1.intersects(path2) // returns a boolean
path1.intersectionPoints(with: path2) // returns an array of points

如果执行许多计算,您可以通过创建 CGPathImage 来提高性能。在预先存在的 CGPathImage 上执行的任何计算将比在原始 CGPath 上执行的相同计算运行得更快。

import CGPathIntersection

let pathImage = CGPathImage(from: CGPath(...))
let otherPathImages: [CGPathImage] = [...]

let intersectingPaths = otherPathImages.filter { pathImage.intersects($0) }

示例

CGPathIntersection 是作为 Streets 的一个组件创建的,这是一个模拟管理街道网络的 SpriteKit 游戏原型。 Streets 使用 CGPathIntersection 将各个道路与物理交叉口连接在一起。 当汽车到达十字路口时,它会随机转弯进入另一条相连的道路。

Streets 也对更复杂的路径提供了一些支持,例如环形交叉路口