Swift:UIBezierPath填充2条路径的交集

时间:2018-11-21 15:54:55

标签: 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
}

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

如果您的日期是单独的UILabel,则可以通过将UIView作为日历的子代放在带有日期的标签下,从而完全跳过此呈现和路径填充问题。给它提供背景颜色和圆角(照常使用ActiveRoomsIds)。那会帮你照顾好你的四角形。