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

后端 未结 2 1073
时光说笑
时光说笑 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

    To draw a sine wave on a UIBezierPath called path, draw a number of line segments using path.addLine(to:). The trick is to convert the angle (0 to 360) to the x coordinate of a point, and sin(x) to the y coordinate of a point.

    Here is an example:

    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
    

    Here it is running in a Playground:


    @Rob updated this code making it @IBDesignable with @IBInspectable properties in addition to adding a periods property. Check out his answer here.

提交回复
热议问题