swift - 在一个上下文中绘制实线和虚线

标签 swift core-graphics

我想在一个上下文中画一条虚线和一条实线。但是如果我先画一条虚线,第二条线也是一条虚线。那么如何清理context.setLineDash呢?我尝试了 context.beginContext(),但没有用。

代码如下:

if let context = UIGraphicsGetCurrentContext() {
    // The first line
    let startPoint = CGPoint(x: 20, y: rect.height/2)
    let endPoint = CGPoint(x: rect.width - 40, y: rect.height/2)
    context.move(to: startPoint)
    context.addLine(to: endPoint)
    context.setLineWidth(1)
    context.setLineDash(phase: 0, lengths: [4, 4])
    context.setStrokeColor(UIColor.progressDashLineColor.cgColor)
    context.strokePath()
    // Second line
    let startPoint1 = CGPoint(x: 20, y: rect.height/2 + 5)
    let endPoint1 = CGPoint(x: rect.width-120, y: rect.height/2)
    context.setStrokeColor(UIColor.mainColor.cgColor)
    context.setLineWidth(5)
    context.move(to: startPoint1)
    context.addLine(to: endPoint1)
    context.setLineCap(.round)
    context.strokePath()
}

最佳答案

在绘制实线之前将虚线设置为空数组。

context.setLineDash(phase: 0, lengths: [])

来自 CGContext 文档:

Pass an empty array to clear the dash pattern so that all stroke drawing in the context uses solid lines.

Documentation Link

关于swift - 在一个上下文中绘制实线和虚线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46005023/

相关文章:

ios - 尝试在已经呈现 UIAlertController 的 ViewController 上呈现 UIViewController

ios - CGFloat 的目的是什么

swift - CGPoint 读数在 500,000,000 的极端坐标处不准确

swift - UIBezierPath roundedRect - 改变角的颜色

objective-c - 我可以用一种颜色和不同颜色的边框描边路径吗?

swift - 滚动时如何防止 UILabel.textColor 在 dequeueReusableCell 中发生变化?

swift - Xcode Swift 快速帮助闭包

swift - 从 Firestore 填充 UITableView

swift - Xcode 索引需要很长时间并使用千兆字节的内存

ios - 尝试使用渐变进行实时绘图时出现性能问题