我正在使用 2 UIBezierPath
创建一个矩形和一个半圆形。它工作正常,但我无法用颜色填充交叉点。
这是我的 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/