How do I draw a cosine or sine curve in Swift?

后端 未结 2 1079
时光说笑
时光说笑 2020-12-18 14:12

I\'ve been trying to figure out how to use UIBezierPath for this project, but I don\'t know how to implement this kind of drawing. I can draw a circle and arcs and straight

2条回答
  •  渐次进展
    2020-12-18 14:53

    This allows you to place a sine wave inside a rect:

        func generateWave(cycles: Int, inRect: CGRect, startAngleInDegrees: CGFloat = 0) -> UIBezierPath {
            let dx = inRect.size.width
            let amplitude = inRect.size.height
            let scaleXToDegrees = 1 / (inRect.size.width / 360.0 / CGFloat(cycles))
            let path = UIBezierPath()
            for x in stride(from: 0, to: dx + 5, by: 5) {
                let y = sin(D2R(startAngleInDegrees + x * scaleXToDegrees)) * amplitude / 2
                let p = CGPoint(x: x + inRect.origin.x, y: y + inRect.origin.y)
                if x == 0 {
                    path.move(to: p)
                } else {
                    path.addLine(to: p)
                }
            }
            return path
        }
    

    To animate:

        override func update(_ currentTime: TimeInterval) {
            shape?.removeFromParent()
    
            let path = generateWave(cycles: 7, inRect: targetRect, startAngleInDegrees: currentStartAngle)
            shape = SKShapeNode(path: path.cgPath)
            shape!.strokeColor = .red
            shape!.lineWidth = 1
            self.addChild(shape!)
            currentStartAngle += 5
        }
    

提交回复
热议问题