iOS Outline of Stroked UIBezierPath/CGPath,作为路径

标签 ios swift core-graphics uibezierpath cgpath

(我已经阅读了关于 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 的调试器预览会友好地呈现结果:

enter image description here

我需要这些点作为路径。

第一次尝试,使用现代版本的CGPathCreateCopyByStrokingPath()

let strokedCGPath = bezierPath.cgPath.copy(strokingWithWidth: dotWidth,
    lineCap: lineCapStyle,
    lineJoin: lineJoinStyle,
    miterLimit: 4)

enter image description here

第二次尝试:

let dashedCGPath = bezierPath.cgPath.copy(dashingWithPhase: 0, lengths: dashes)

enter image description here

结果:copy(strokingWithWidth:)copy(dashingWithPhase:) 都没有给我所需的完整路径。

问题:我在这里遗漏了什么明显的东西吗?有没有办法得到笔划的整个路径?

感谢您的帮助。

最佳答案

[编辑]

我之前的回答不正确。

在这种情况下,使用 CGPath 的 copy(dashingWithPhase: phase, lengths: pattern) 将不起作用。尽管有该方法的描述,它实际上不会生成生成的笔划的完整轮廓路径。

一个可行的解决方案是:

  • 创建一个临时的CGContext

  • 在上下文中,设置所有与笔划相关的参数,例如 lineCaplineWidthlineJoin,最重要的是,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/

相关文章:

objective-c - NSString从return方法返回空

ios - CKDatabaseSubscription 不推送通知

swift - 页面打开时给 UILabel 添加动画

ios - 移动 CALayer 框架但不移动剪辑蒙版

ios - 在使用 Alamofire + suggestedDownloadDestination 下载文件之前检查文件是否已经存在

ios - 核心数据,将数据加载到UITextView中

ios - 如何在 CAEmitterCell 的入口处设置动画?

ios - UIView 不从底部向上滑动

iphone - iOS - 如何在 View 中绘制透明三角形

iphone - 绘制白色会产生透明色