Skip to content

Instantly share code, notes, and snippets.

@juliantejera
Last active July 1, 2017 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliantejera/6c8a1f6e42fbc070024b954c569bfc2b to your computer and use it in GitHub Desktop.
Save juliantejera/6c8a1f6e42fbc070024b954c569bfc2b to your computer and use it in GitHub Desktop.
How to draw a rainbow with Bezier Paths
//: Playground - noun: a place where people can play
import UIKit
import Foundation
import PlaygroundSupport
extension UIColor {
class var indigo: UIColor {
return UIColor(colorLiteralRed: 75.0/255.0, green: 0, blue: 130.0/255.0, alpha: 1)
}
class var violet: UIColor {
return UIColor(colorLiteralRed: 139.0/255.0, green: 0, blue: 255.0/255.0, alpha: 1)
}
static let rainbow = [
UIColor.red,
UIColor.orange,
UIColor.yellow,
UIColor.green,
UIColor.blue,
UIColor.indigo,
UIColor.violet
]
}
class RainbowView: UIView {
override func draw(_ rect: CGRect) {
let paths = rainbowBezierPaths(rect: rect)
for (index, path) in paths.enumerated() {
draw(bezierPath: path, color: UIColor.rainbow[index])
}
}
private func draw(bezierPath: UIBezierPath, color: UIColor) {
color.setStroke()
color.setFill()
bezierPath.stroke()
}
private func rainbowBezierPaths(rect: CGRect) -> [UIBezierPath] {
let gapFactor: CGFloat = 0.90
let diameter = max(rect.maxX, rect.midY)
let maxRadius: CGFloat = (diameter / 2.0) * gapFactor
let arcCenter = CGPoint(x: rect.midX, y: rect.midY + (maxRadius / 2.0))
let lineWidth: CGFloat = maxRadius / CGFloat(UIColor.rainbow.count) / 2.0
var paths = [UIBezierPath]()
for index in 0..<(UIColor.rainbow.count) {
let radius = maxRadius - (CGFloat(index) * lineWidth)
let path = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: 0, endAngle: CGFloat.pi, clockwise: false)
path.lineWidth = lineWidth
paths.append(path)
}
return paths
}
}
let rainbowView = RainbowView(frame: CGRect(x: 0, y: 0, width: 800, height: 800))
rainbowView.backgroundColor = .white
PlaygroundPage.current.liveView = rainbowView
@juliantejera
Copy link
Author

screen shot 2017-06-30 at 9 37 41 pm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment