【问题标题】:Swift Combine and reverse UIBezierPathsSwift 组合和反转 UIBezierPaths
【发布时间】:2021-11-30 15:27:30
【问题描述】:
我面临的问题是反转子路径。举个例子:
let circlePaths: [UIBezierPath] = ...
let rectanglePath: UIBezierPath = ... // a rectangle
let totalPath: UIBezierPath = .init()
for path in circlePaths {
totalPath.append(path)
}
rectanglePath.append(totalPath)
应该是这样的:
现在理想情况下我想用
剪掉所有的圆圈
bezierPath.append(totalPath.reversing())
但是效果不如预期。我希望这两个圆圈组成一条路径并且这个路径是相反的,但实际上两个圆圈路径都是相反的,这导致交叉点成为路径的一部分(reversing() 两次没有效果)。我想将圆形路径组合成一个,交叉点不存在,但作为路径的一部分。我希望较小的圆圈将较大的圆圈“扩展”为路径。
知道我会怎么做吗?
编辑 1:这是生成路径的图像。
【问题讨论】:
标签:
swift
uikit
uibezierpath
cgpath
【解决方案1】:
如果您需要实际创建单个路径作为多个路径的组合/联合,您可能需要查看其中一个库。
但是,如果您只需要 视觉输出,这可能是一种可用的方法。
- 创建 3 条路径 -- 外矩形、大圆、小圆。
- 描边并填充外部矩形路径
- 绘制两条圆形路径
- 填充两条圆形路径
一个例子UIView类:
class FakeUnionUIBezierPaths : UIView {
override func draw(_ rect: CGRect) {
// yellow line width
let lWidth: CGFloat = 8
// paths are stroked on the center, so
// use one-half the line width to adjust ediges
let hWidth: CGFloat = lWidth * 0.5
// border / outer rect, inset by one-half line width
let dRect: CGRect = rect.insetBy(dx: hWidth, dy: hWidth)
// first circle
// full-height
// aligned to left edge
var c1Rect: CGRect = dRect
c1Rect.size.width = c1Rect.height
// second circle
// half-height
// aligned to right edge
var c2Rect: CGRect = dRect
c2Rect.size.height *= 0.5
c2Rect.size.width = c2Rect.height
c2Rect.origin.x = dRect.width - c2Rect.width + hWidth
c2Rect.origin.y = dRect.height * 0.25
let pRect: UIBezierPath = UIBezierPath(rect: dRect)
let p1: UIBezierPath = UIBezierPath(ovalIn: c1Rect)
let p2: UIBezierPath = UIBezierPath(ovalIn: c2Rect)
UIColor.yellow.setStroke()
UIColor.blue.setFill()
// same line-width for all three paths
[pRect, p1, p2].forEach { p in
p.lineWidth = lWidth
}
// stroke and fill the border / outer rect
pRect.stroke()
pRect.fill()
// stroke both circle paths
p1.stroke()
p2.stroke()
// fill both circle paths
p1.fill()
p2.fill()
}
}
输出: