ios - 使用closePath函数关闭贝塞尔路径和手动关闭有什么区别?

标签 ios core-graphics uibezierpath

我正在尝试使用 UIBezierPath 制作一个矩形。我采用了两种不同的方式来绘制它。另外,我将描边宽度增加到 25 像素。

第一种方法:使用 closePath

UIBezierPath *bpath = [UIBezierPath bezierPath];
    
[bpath moveToPoint:CGPointMake(x, y)];
[bpath addLineToPoint:CGPointMake(x + w, y)];
[bpath addLineToPoint:CGPointMake(x + w, y + h)];
[bpath addLineToPoint:CGPointMake(x, y + h)];
[bpath closePath];

输出:

Using closePath

第二种方法:手动关闭路径

UIBezierPath *bpath = [UIBezierPath bezierPath];
    
[bpath moveToPoint:CGPointMake(x, y)];
[bpath addLineToPoint:CGPointMake(x + w, y)];
[bpath addLineToPoint:CGPointMake(x + w, y + h)];
[bpath addLineToPoint:CGPointMake(x, y + h)];
[bpath addLineToPoint:CGPointMake(x, y)];

输出:

Closing path manually

closePath 的文档中说 此方法通过在子路径的第一个点和最后一个点之间创建一条线段来关闭当前子路径。此方法随后将当前点更新为新创建的线段的末尾,这也是现在关闭的子路径中的第一个点。

在第二种方法中,我在第一个点和最后一个点之间创建线段。那么,为什么在第二种方法中矩形没有被完全描边呢?

注意:只有当笔划宽度显着增加时,这些方法之间的差异才可见。

最佳答案

区别在于 [closePath] 方法实际上向支持 UIBezierPath 的底层 CGPath 添加了一个额外的路径元素。

如果您使用[closePath],那么一个类型为kCGPathElementCloseSubpath 的附加CGPathElement 将立即附加到路径的末尾在最后一个线段之后。

这在使用文档中 UIBezierPath 的 [containsPoint:] 方法时尤为重要:

A point is not considered to be enclosed by the path if it is inside an open subpath, regardless of whether that area would be painted during a fill operation. Therefore, to determine mouse hits on open paths, you must create a copy of the path object and explicitly close any subpaths (using the closePath method) before calling this method.

关于ios - 使用closePath函数关闭贝塞尔路径和手动关闭有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25806995/

相关文章:

ios - 我无法在 Swift 中解决 "Use of undeclared type ' SphereNode'"

ios - 使用多维数组创建 @property

ios - 在 iOS 中绘图时计算控制点

iphone - 在 UIImage 之上添加图像

ios - CGlayer 绘图性能低下

ios - 如何使用 UIBezierPathwithArcCenter 在 iOS 中绘制一个完整的圆?

iOS:如何正确安装保持事件处理程序?

iOS 应用程序切片或细化不起作用

ios - Swift 中的圆圈 - 无法摆脱剪裁

ios - 形成封闭路径的 UIBezierPath 子路径不能在 SVG 中表示