Last active
July 1, 2017 01:41
-
-
Save juliantejera/6c8a1f6e42fbc070024b954c569bfc2b to your computer and use it in GitHub Desktop.
How to draw a rainbow with Bezier Paths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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 |
Author
juliantejera
commented
Jul 1, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment