Created
August 29, 2017 18:14
-
-
Save KaiCode2/450de341f6eeb05adff58983f424dfbb to your computer and use it in GitHub Desktop.
Core Graphics experiment: draw a star
This file contains 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 PlaygroundSupport | |
internal final class StarView: UIView { | |
let numberOfEdges = 5 | |
let fillColor: UIColor = .red | |
let strokeColor: UIColor = .black | |
let lineWidth: CGFloat = 2 | |
let innerRadiusRatio: CGFloat = 0.5 | |
let outerRadius: CGFloat = 50 | |
override func draw(_ rect: CGRect) { | |
guard let context = UIGraphicsGetCurrentContext() else { return } | |
//Draw your stuff in here... | |
let origin = CGPoint(x: rect.width / 2, y: rect.height / 2) | |
let angle = 360 / numberOfEdges | |
let lines = (0..<numberOfEdges * 2).map { (index) -> CGPoint in | |
var point = origin | |
let radius = index % 2 == 0 ? outerRadius : (outerRadius * innerRadiusRatio) | |
let pointRotation = index % 2 == 0 ? CGFloat(angle * index) : CGFloat(angle * index) + CGFloat(angle / 2) | |
point.y -= radius | |
point = point.rotate(around: origin, with: pointRotation) | |
return point | |
} | |
context.addLines(between: lines) | |
context.setStrokeColor(strokeColor.cgColor) | |
context.setFillColor(fillColor.cgColor) | |
context.setLineWidth(lineWidth) | |
context.fillPath() | |
} | |
} | |
extension CGPoint { | |
func rotate(around center: CGPoint, with degrees: CGFloat) -> CGPoint { | |
let dx = self.x - center.x | |
let dy = self.y - center.y | |
let radius = sqrt(dx * dx + dy * dy) | |
let azimuth = atan2(dy, dx) // in radians | |
let newAzimuth = azimuth + degrees * CGFloat(M_PI / 180.0) // convert it to radians | |
let x = center.x + radius * cos(newAzimuth) | |
let y = center.y + radius * sin(newAzimuth) | |
return CGPoint(x: x, y: y) | |
} | |
} | |
let view = StarView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) | |
view.backgroundColor = .white | |
PlaygroundPage.current.needsIndefiniteExecution = false | |
PlaygroundPage.current.liveView = view |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment