【问题标题】:CoreGraphics zigzag and hash line between 2 CGPointCoreGraphics 之字形和 2 个 CGPoint 之间的哈希线
【发布时间】:2025-12-21 11:20:08
【问题描述】:

我正在使用 Swift 构建一个 iOS 项目。 如何使用 CoreGraphics 绘制 zig-zag 路径?如何计算所有的中间点?

我还需要画一个散列线?这可以用 CoreGraphics 创建吗?

作为我尝试实现的示例:

【问题讨论】:

  • 有多种方法可以做到这一点-包括抚摸UIBezierPath和/或使用CAReplicatorLayer。到目前为止你完成了什么?你能画一条线吗?
  • @DonMag 我可以画线和其他物体。我还找到了如何根据起点和终点计算箭头线的算法。我正在寻找一种方法来创建或自定义路径(点之间)或算法来识别曲折的点。
  • 好的 - 但需要更多信息。你想要一个预定的“步长”——你需要在哪里计算步数?或者,您是否需要预先确定的步数 - 您需要在哪里计算“步长”?
  • 步长总是一样的(20),想法是首先用户添加之字形(一触,touchPoint是起点,终点是左边200),但是何时移动之字形线的一端将根据起点和终点重绘(考虑到这两个点可以在画布中的任何位置)。我已经准备好如何移动线的末端,我只需要找出如何计算之字形的中间点。

标签: ios swift core-graphics


【解决方案1】:

一般的想法是:

  • 获取宽度:pt2.x - pt1.x
  • 获取高度:pt2.y - pt1.y
  • 步宽为 20,所以宽度除以 20 得到步数
  • step-height 将是高度/步数
  • 创建一个UIBezierPath
  • 循环遍历步数,增加.lineTo(pt) 的 x 和 y 值

这是一个示例 - 请注意,它没有错误处理,如果pt2在右侧且低于pt1,则需要额外的逻辑:

class SampleCGView: UIView {
    
    var pt1: CGPoint = .zero
    var pt2: CGPoint = .zero
    
    override func draw(_ rect: CGRect) {

        // green line to show pt1 to pt2
        let linePath: UIBezierPath = UIBezierPath()
        linePath.move(to: pt1)
        linePath.addLine(to: pt2)
        UIColor.green.setStroke()
        linePath.stroke()
        
        let zigzagPath: UIBezierPath = UIBezierPath()
        let numSteps: CGFloat = (pt2.x - pt1.x) / 20.0
        // step width is 20
        let xInc: CGFloat = 20
        // step height is based on line angle
        let yInc: CGFloat = (pt2.y - pt1.y) / numSteps
        var pt: CGPoint = pt1
        zigzagPath.move(to: pt)
        for _ in 1...Int(numSteps) {
            zigzagPath.addLine(to: CGPoint(x: pt.x + xInc * 0.75, y: pt.y - yInc * 0.25))
            zigzagPath.addLine(to: CGPoint(x: pt.x + xInc, y: pt.y + yInc))
            pt.x += xInc
            pt.y += yInc
        }
        UIColor.black.setStroke()
        zigzagPath.stroke()
        
    }
    
}

要演示的示例视图控制器:

class SampleDrawViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let v = SampleCGView()
        v.backgroundColor = .systemYellow
        v.translatesAutoresizingMaskIntoConstraints = false
        
        view.addSubview(v)
        
        let g = view.safeAreaLayoutGuide
        
        NSLayoutConstraint.activate([
            v.topAnchor.constraint(equalTo: g.topAnchor, constant: 80.0),
            v.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 40.0),
            v.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -40.0),
            v.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -80.0),
        ])
        
        // set start and end points for the zigzag line
        v.pt1 = CGPoint(x: 40, y: 40)
        v.pt2 = CGPoint(x: 260, y: 160)
        
    }
}

结果(绘制绿线只是为了使pt1pt2 位置清晰):

【讨论】: