Skip to content

Instantly share code, notes, and snippets.

@sooop
Created February 21, 2017 00:58
Show Gist options
  • Select an option

  • Save sooop/3a45eba0c9c691c97bdf41c7ff8f65bb to your computer and use it in GitHub Desktop.

Select an option

Save sooop/3a45eba0c9c691c97bdf41c7ff8f65bb to your computer and use it in GitHub Desktop.
/// Polynomial.swift
import Cocoa
fileprivate let HOPS = 100
fileprivate RANDFLOAT: () -> CGFloat = {
return CGFloat(arc4random % 128) % 128.0
}
fileprivate let funcRect = CGRect(x: -20, y: -20, width: 40, height: 40)
class Polynomial: NSObject {
var terms = [CGFloat]()
var termCount: Int = 0
var color: CGColor?
override init() {
super.init()
color = CGColor(red: RANDFLOAT(), green: RANDFLOAT(), blue: RANDFLOAT(), alpha: 0.5)
// CFMakeCollectiable()은 없어졌다...
termCount = Int(arc4random()) % 3 + 2
terms = (0..<termCount).map{ _ in
return 5.0 - CGFloat(arc4random() % 100) / 10.0
}
}
func value(at x: CGFloat) -> CGFloat {
return terms.reduce(0, {$0 * x + $1 })
}
func draw(in rect: CGRect, context ctx: CGContext) {
ctx.saveGstate()
let tf = CGAffineTransform(a: rect.width / funcRect.width,
b: 0,
c: 0,
d: rect.height / funcRect.height,
tx: rect.width / 2,
ty: rect.height / 2)
ctx.concatenate(tf)
ctx.setStrokeColor(color)
ctx.setLineWidth(0.4)
let distance = funcRect.width / HOPS
var currentX = funcRect.minX
var first = true;
while currentX <= funcRect.maxX {
let currentY = value(at: currentX)
if first {
ctx.move(CGPoint(x: currentX, y: currentY))
first = false
} else {
addLine(to: CGPoint(x: currentX, y: currentY))
}
currentX += distance
}
ctx.strokePath()
ctx.restoreGState()
}
// finalize는 deprecated됨.
}
/// PolynomialView.swift
import Cocoa
class PolynomialView: NSView {
var polynomials = [Polynomial]()
@IBAction func createNewPolynomial(_ sender: Any) {
let p = Polynomial()
polynomials.append(p)
setNeedsDisplay(bounds)
}
@IBAction func deleteRandomPolynomial(_ sender: Any) {
guard !polynomials.isEmpty else { return }
let i = Int(arc4random()) % polynomials.count
polynomials.remove(at: i)
setNeedsDisplay(bounds)
}
override func draw(_ rect: CGRect) {
NSColor.whiteColor.set()
NSBezierPath.fill(bounds)
if let ctx = NSGraphicsContext.current() {
polynomials.forEach{ $0.draw(in: self.bounds, context: ctx) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment