如何在Swift中绘制余弦或正弦曲线?

ɯɐɹ*_*ɐɹʞ 1 uibezierpath swift

我一直在试图弄清楚如何在这个项目中使用UIBezierPath,但我不知道如何实现这种绘图.我可以绘制一个圆弧,直线和直线,但我觉得这个很丢失.感谢帮助

vac*_*ama 14

要在UIBezierPath被调用上绘制正弦波path,请使用绘制多个线段path.addLine(to:).诀窍是将角度(0to 360)转换x为点sin(x)y坐标,并转换为点的坐标.

这是一个例子:

class SineView: UIView{
    let graphWidth: CGFloat = 0.8  // Graph is 80% of the width of the view
    let amplitude: CGFloat = 0.3   // Amplitude of sine wave is 30% of view height

    override func draw(_ rect: CGRect) {
        let width = rect.width
        let height = rect.height

        let origin = CGPoint(x: width * (1 - graphWidth) / 2, y: height * 0.50)

        let path = UIBezierPath()
        path.move(to: origin)

        for angle in stride(from: 5.0, through: 360.0, by: 5.0) {
            let x = origin.x + CGFloat(angle/360.0) * width * graphWidth
            let y = origin.y - CGFloat(sin(angle/180.0 * Double.pi)) * height * amplitude
            path.addLine(to: CGPoint(x: x, y: y))
        }

        UIColor.black.setStroke()
        path.stroke()
    }
}

let sineView = SineView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
sineView.backgroundColor = .white
Run Code Online (Sandbox Code Playgroud)

它在Playground中运行:

正弦波在操场上


@Rob更新该代码使得它@IBDesignable@IBInspectable另外属性添加periods属性.在这里查看他的答案.