Skip to content

Instantly share code, notes, and snippets.

@mihai-salari
Forked from soggybag/ViewController.swift
Created October 16, 2017 12:08
Show Gist options
  • Save mihai-salari/2223d9214fa370393ccea58f7e8ea199 to your computer and use it in GitHub Desktop.
Save mihai-salari/2223d9214fa370393ccea58f7e8ea199 to your computer and use it in GitHub Desktop.
Short snippet for drawing a sine curve with UIBezierPath
// Draw a sine curve
let centerY = frame.height / 2 // find the vertical center
let steps = 200 // Divide the curve into steps
let stepX = frame.width / CGFloat(steps) // find the horizontal step distance
// Make a path
let path = UIBezierPath()
// Move the starting point to the left center
path.moveToPoint(CGPoint(x: 0, y: centerY))
// Loop and draw steps in straingt line segments
for i in 0...steps {
let x = CGFloat(i) * stepX
let y = CGFloat(i) % 2 * 10 + centerY
let y2 = (sin(Double(i) * 0.1) * 40) + Double(centerY)
path.addLineToPoint(CGPoint(x: x, y: CGFloat(y2)))
}
/*
let path = UIBezierPath(rect: CGRect(x: 10, y: 10, width: 40, height: 40))
*/
// Render the path
let strokeColor = UIColor.redColor()
strokeColor.setStroke()
path.lineWidth = 3
path.stroke()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment