ios - Swift:UIBezierPath 填充两条路径的交集

标签 ios swift

我正在使用 2 UIBezierPath 创建一个矩形和一个半圆形。它工作正常,但我无法用颜色填充交叉点。

enter image description here

这是我的 drawCircle 和我的 addPaths 函数:

private func drawCircle(selectedPosition: SelectionRangePosition, currentMonth: Bool) {
    circleView.layer.sublayers = nil

    let radius = contentView.bounds.height/2
    let arcCenter = CGPoint(x: ceil(contentView.bounds.width/2), y: ceil(contentView.bounds.height/2))
    let circlePath = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: .pi/2, endAngle: .pi * 3/2, clockwise: selectedPosition == .left)

    let semiCircleLayerPath = UIBezierPath()
    let semiCircleLayer   = CAShapeLayer()
    semiCircleLayer.fillColor = UIColor.tealish.cgColor

    circleView.layer.addSublayer(semiCircleLayer)

    switch (selectedPosition, currentMonth) {
    case (.left, true):
        let rectanglePath = UIBezierPath(rect: CGRect(x: contentView.bounds.width / 2, y: 0, width: ceil(contentView.bounds.width / 2), height: contentView.bounds.height))
        addPaths(semiCircleLayerPath, rectanglePath, circlePath, semiCircleLayer)

    case (.middle, true):
        backgroundColor = .tealish

    case (.right, true):

    // Note: The + 10 is just to overlap the shapes and test if the filling works

        let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: ceil(contentView.bounds.width / 2) + 10, height: contentView.bounds.height))
        addPaths(semiCircleLayerPath, rectanglePath, circlePath, semiCircleLayer)

    default:
        backgroundColor = .clear

    }
}

private func addPaths(_ semiCircleLayerPath: UIBezierPath, _ rectanglePath: UIBezierPath, _ circlePath: UIBezierPath, _ semiCircleLayer: CAShapeLayer) {
    semiCircleLayerPath.append(circlePath)
    semiCircleLayerPath.append(rectanglePath)

    semiCircleLayer.path = semiCircleLayerPath.cgPath
}

最佳答案

问题是半圆路径和矩形路径是在相反的方向上添加的。不幸的是,这是 Cocoa API 添加它们的方式的一个功能;在您的情况下,这意味着交叉点的“环绕计数”为 0。

幸运的是,有一个简单的解决方法:为半圆和矩形创建单独的路径。当分别填写它们时,您应该会得到想要的结果。

不幸的是,这将意味着您不能仅使用图层绘制:您将需要使用 drawRect 方法绘制背景。

关于ios - Swift:UIBezierPath 填充两条路径的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53415870/

相关文章:

iOS:WKWebview 如何允许位于 bundle 中的 html 文件读取文档目录

iphone - UIView 3DCube 像 Clear-app

swift - 当宽度为设备宽度且高度为原始图像的高度时,UIImageView 中的图像将被裁剪

ios - dyld : Library not loaded: @rpath/Alamofire. 框架/Alamofire 和 AlamofireImage

objective-c - 将选定的日期和时间保存到plist中

ios - 在 IOS 中使用 PJSIP 注册远程 VOIP 服务器

ios - 在点击的链接上缩放网页

swift - 如何快速停止 Sprite 套件更新?

swift - 如何在 swift 中接受 RateController 的评级值作为字符串

swift - convenience init vs init in swift, explicit examples better 有什么区别