两个UIBezierPaths交集作为UIBezierPath

Ama*_*aed 6 ios uibezierpath swift swift3

我有两个UIBezierPaths,一个代表图像部分的多边形,另一个是要在其上绘制的路径.

我需要找到它们之间的交点,以便只有该交叉区域内的点才会被着色.

有没有一种方法UIBezierPath可以在两条路径之间找到交叉点或新路径?

jrt*_*ton 9

我不知道获取新路径的方法是两条路径的交集,但是您可以使用每条路径的裁剪属性填充或以其他方式绘制交叉点.

在此示例中,有两个路径,正方形和圆形:

let path1 = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 100, height: 100))
let path2 = UIBezierPath(ovalIn: CGRect(x:50, y:50, width: 100, height: 100))
Run Code Online (Sandbox Code Playgroud)

我制作一个渲染器来绘制这些,但你可以在drawRect任何地方或任何地方执行此操作:

let renderer = UIGraphicsImageRenderer(bounds: CGRect(x: 0, y: 0, width: 200, height: 200))
let image = renderer.image {
    context in
    // You wouldn't actually stroke the paths, this is just to illustrate where they are
    UIColor.gray.setStroke()
    path1.stroke()
    path2.stroke()
    // You would just do this part
    path1.addClip()
    path2.addClip()
    UIColor.red.setFill()
    context.fill(context.format.bounds)
}
Run Code Online (Sandbox Code Playgroud)

生成的图像看起来像这样(为了清晰起见,我在代码注释中指示了每条路径,实际上你只做填充部分):

在此输入图像描述


ada*_*ulf 7

我编写了一个UIBezierPath库,它允许您根据相交路径将给定的闭合路径切割为子形状.它基本上完全符合您的要求:https://github.com/adamwulf/ClippingBezier

NSArray<UIBezierPath*>* componentShapes = [shapePath uniqueShapesCreatedFromSlicingWithUnclosedPath:scissorPath];
Run Code Online (Sandbox Code Playgroud)

或者,您也可以找到交叉点:

NSArray* intersections = [scissorPath findIntersectionsWithClosedPath:shapePath andBeginsInside:nil];
Run Code Online (Sandbox Code Playgroud)