Mark Bragg - 1 year ago 155
Swift Question

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

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 lines, but I am feeling pretty lost on this one. Appreciate the help

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
}

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download