Last active
April 20, 2016 05:07
-
-
Save traviskirton/da2989144e2ac038eb8104319a78dc85 to your computer and use it in GitHub Desktop.
Drawing Shapes to a PDF
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
| import UIKit | |
| class WorkSpace: CanvasController { | |
| var pdfContext: CGContext! | |
| var shapes: [Shape]! | |
| override func setup() { | |
| shapes = [Shape]() | |
| for i in 0..<10 { | |
| let center = Point(Double(i) * 30.0, Double(i) * 30.0) | |
| let circle = Circle(center: center, radius: 30.0) | |
| circle.fillColor = Color(red: random01(), green: random01(), blue: random01(), alpha: 1.0) | |
| circle.lineWidth = 1 + 9 * random01() | |
| canvas.add(circle) | |
| shapes.append(circle) | |
| } | |
| draw(shapes, toPDFWithFileName: "hello.pdf") | |
| } | |
| func draw(shapes: [Shape], toPDFWithFileName fileName: String) { | |
| let targetURL = dirtyDesktopDirectory?.URLByAppendingPathComponent(fileName) | |
| guard let p = targetURL?.path else { | |
| print("Could not retrieve path for \(targetURL)") | |
| return | |
| } | |
| UIGraphicsBeginPDFContextToFile(p, CGRectZero, nil) | |
| UIGraphicsBeginPDFPageWithInfo(canvas.view.frame, nil) | |
| for shape in shapes { | |
| let bez = UIBezierPath(CGPath: shape.path!.CGPath) | |
| bez.applyTransform(CGAffineTransformMakeTranslation(CGFloat(shape.origin.x), CGFloat(shape.origin.y))) | |
| var color = UIColor.clearColor() | |
| if shape.fillColor != nil { | |
| color = UIColor(shape.fillColor!)! | |
| } | |
| color.setFill() | |
| bez.fill() | |
| color = UIColor.clearColor() | |
| if shape.strokeColor != nil { | |
| color = UIColor(shape.strokeColor!)! | |
| } | |
| bez.lineWidth = CGFloat(shape.lineWidth) | |
| color.setStroke() | |
| bez.stroke() | |
| //ADD OTHER SHAPE DRAWING OPTIONS HERE | |
| } | |
| UIGraphicsEndPDFContext() | |
| } | |
| var dirtyDesktopDirectory: NSURL? { | |
| let dir = NSSearchPathDirectory.DesktopDirectory | |
| let dom = NSSearchPathDomainMask.AllDomainsMask | |
| let paths = NSSearchPathForDirectoriesInDomains(dir, dom, true) | |
| if let p = paths.first { | |
| print(p) //non-dirty would be to get an accurate value for p | |
| return NSURL(fileURLWithPath: "/Users/travis/Desktop") //<<deeerrrty – put your comp's name where mine is | |
| } | |
| return nil | |
| } | |
| //best to use this, if you're shipping an app, you can access it in iTunes | |
| var applicationDocumentsDirectory: NSURL { | |
| let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) | |
| return urls[urls.endIndex-1] | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment