(我已经阅读了关于 SO 的其他答案,但它们似乎并没有解决手头的问题。)
[ swift 4,Xcode 9]
我需要在路径的 stroke()
之后获取表示绘制区域的路径。即表示笔划轮廓的路径。
给定一个具有以下属性的 UIBezierPath
:
let dotWidth: CGFloat = 3
let spacing: CGFloat = 12
let dashes: [CGFloat] = [0.0, spacing]
let lineCapStyle: CGLineCap = .round
let lineJoinStyle: CGLineJoin = .miter
bezierPath.lineCapStyle = lineCapStyle
bezierPath.lineJoinStyle = lineJoinStyle
bezierPath.setLineDash(dashes, count: dashes.count, phase: 0)
bezierPath.lineWidth = dotWidth
Xcode 的调试器预览会友好地呈现结果:
我需要这些点作为路径。
第一次尝试,使用现代版本的CGPathCreateCopyByStrokingPath()
let strokedCGPath = bezierPath.cgPath.copy(strokingWithWidth: dotWidth,
lineCap: lineCapStyle,
lineJoin: lineJoinStyle,
miterLimit: 4)
第二次尝试:
let dashedCGPath = bezierPath.cgPath.copy(dashingWithPhase: 0, lengths: dashes)
结果:copy(strokingWithWidth:)
或 copy(dashingWithPhase:)
都没有给我所需的完整路径。
问题:我在这里遗漏了什么明显的东西吗?有没有办法得到笔划的整个路径?
感谢您的帮助。
最佳答案
[编辑]
我之前的回答不正确。
在这种情况下,使用 CGPath 的 copy(dashingWithPhase: phase, lengths: pattern)
将不起作用。尽管有该方法的描述,它实际上不会生成生成的笔划的完整轮廓路径。
一个可行的解决方案是:
创建一个临时的
CGContext
在上下文中,设置所有与笔划相关的参数,例如
lineCap
、lineWidth
、lineJoin
,最重要的是,lineDash
将您的路径添加到上下文:
context.addPath(bezierPath.cgPath)
不要调用
fill()
或stroke()
。我们对画画不感兴趣。而是调用
context.replacePathWithStrokedPath()
最后,使用
let newCGPath = context.path
从上下文中拉出一个新的 cgPath
此 newCGPath
将是描边路径的轮廓,就好像它已被绘制一样。
关于iOS Outline of Stroked UIBezierPath/CGPath,作为路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47026578/