swift - 未填充 append 重叠的 UIBezierPath

标签 swift uiview append uibezierpath

我正在尝试使用 UIBezierPath.append 合并两个重叠的 UIBezierPaths,我希望重叠的空间被填充。我尝试将 usesEvenOddFillRule 属性设置为 false,但它仍然没有填充。这是问题的最小示例:

override func draw(_ rect: CGRect) {
    let firstShape = UIBezierPath()

    firstShape.move(to: CGPoint(x: 100, y: 100))
    firstShape.addLine(to: CGPoint(x: 100, y: 150))
    firstShape.addLine(to: CGPoint(x: 150, y: 170))
    firstShape.close()

    let secondShape = UIBezierPath(rect: CGRect(x: 125, y: 125, width: 75, height: 75))

    let combined = UIBezierPath()
    combined.append(firstShape)
    combined.append(secondShape)

    UIColor.black.setFill()
    combined.fill()
}

这会产生以下形状:

Shape

我希望它看起来像什么:

Wanted shape

在一个 UIBezierPath 上使用 move(to: CGPoint) 时似乎也会出现此问题。如果您在同一个 UIBezierPath 上绘制这两个形状,则会出现同样的问题。

有谁知道如何填充重叠区域?最好该解决方案在执行 addClip()

时也有效

最佳答案

您将 usesEvenOddFillRule 设置为 false,走在了正确的轨道上。除此之外,您需要确保您的形状都沿相同的方向绘制(顺时针或逆时针)。

我在绘制三角形时颠倒了你的 addLine 的顺序。

override func draw(_ rect: CGRect) {
    let firstShape = UIBezierPath()

    firstShape.move(to: CGPoint(x: 100, y: 100))
    firstShape.addLine(to: CGPoint(x: 150, y: 170))
    firstShape.addLine(to: CGPoint(x: 100, y: 150))
    firstShape.close()

    let secondShape = UIBezierPath(rect: CGRect(x: 125, y: 125, width: 75, height: 75))

    let combined = UIBezierPath()
    combined.append(firstShape)
    combined.append(secondShape)
    combined.usesEvenOddFillRule = false

    UIColor.black.setFill()
    combined.fill()
}

关于swift - 未填充 append 重叠的 UIBezierPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43168714/

相关文章:

ios - 可选类型字符串的值?没有打开

swift - EXC_BAD_ACCESS 错误,无信息

iphone - 如何在纵向模式应用程序中滑入 UIView?

javascript - 带有 Angular 的 Rails - uiView 未定义

ios - UIView 捕获单指 Action ,但发送两指捏合以查看后面

ios - 避免/禁用 iOS 中的状态保存

swift - 多个窗口 Controller - swift

r - 如何在不跟踪索引的情况下将元素 append 到列表中?

python - 如何将新数据 append 到新行

ios - 如何在 iOS sdk 的本地资源 txt 文件中 append 字符串