Last active
August 29, 2015 14:09
-
-
Save sketchytech/7e7c48f5bbce1bb61228 to your computer and use it in GitHub Desktop.
Swift: Translation and Rotation of CGContext (iOS/Xcode)
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
// This code accompanies the following post: http://sketchytech.blogspot.co.uk/2014/11/swift-translating-and-rotating.html | |
import UIKit | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
let newView = View(frame: CGRect(x: 0, y: 0, width: CGRectGetWidth(self.view.frame), height: CGRectGetHeight(self.view.frame))) | |
self.view.addSubview(newView) | |
} | |
} | |
class View:UIView { | |
override func drawRect(rect:CGRect) | |
{ | |
// obtain context | |
let ctx = UIGraphicsGetCurrentContext() | |
// Decide on radius | |
let rad = CGRectGetWidth(rect)/3.5 | |
// End angle will be 2*pi for any circle that begins at 0 | |
let endAngle = CGFloat(2*M_PI) | |
// We could use CGContextAddEllipseInRect to draw a circle instead | |
CGContextAddArc(ctx, CGRectGetMidX(rect), CGRectGetMidY(rect), rad, 0, endAngle, 1) | |
// set stroke color | |
CGContextSetStrokeColorWithColor(ctx,UIColor.whiteColor().CGColor) | |
// Set line width | |
CGContextSetLineWidth(ctx, 4.0) | |
CGContextStrokePath(ctx) | |
// save current state of context | |
CGContextSaveGState(ctx) | |
CGContextTranslateCTM(ctx, CGRectGetMidX(rect), CGRectGetMidY(rect)) | |
// rotation supplied in radians | |
CGContextRotateCTM(ctx, CGFloat(M_PI*45/180)) | |
// create a mutable path | |
let path = CGPathCreateMutable() | |
// move to the starting point of the path | |
CGPathMoveToPoint(path, nil, 0, 0) | |
// add a line the length of the radius to path | |
CGPathAddLineToPoint(path, nil, rad, 0) | |
// add the path to the (translated and rotated) context | |
CGContextAddPath(ctx, path) | |
// set line width | |
CGContextSetLineWidth(ctx, 4) | |
// set line color | |
CGContextSetStrokeColorWithColor(ctx,UIColor.whiteColor().CGColor) | |
// stroke path | |
CGContextStrokePath(ctx) | |
// restore original state | |
CGContextRestoreGState(ctx) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment