Skip to content

Instantly share code, notes, and snippets.

@sketchytech
Last active August 29, 2015 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sketchytech/ccc85d26b9ad0b2b9277 to your computer and use it in GitHub Desktop.
Save sketchytech/ccc85d26b9ad0b2b9277 to your computer and use it in GitHub Desktop.
Clock face with second markers
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: CGRectGetWidth(self.view.frame)))
self.view.addSubview(newView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
func degree2radian(a:CGFloat)->CGFloat {
let b = CGFloat(M_PI) * a/180
return b
}
func drawSecondMarker(#ctx:CGContextRef, #x:CGFloat, #y:CGFloat, #radius:CGFloat, #color:UIColor) {
var path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, radius, 0);
CGPathAddLineToPoint(path, nil, x, y);
CGPathCloseSubpath(path);
CGContextAddPath(ctx, path);
CGContextSetLineWidth(ctx, 1.5)
CGContextSetStrokeColorWithColor(ctx,color.CGColor);
CGContextStrokePath(ctx);
}
class View: UIView {
override func drawRect(rect:CGRect)
{
var ctx = UIGraphicsGetCurrentContext()
// MARK: Create back of watchface
let rad = CGRectGetWidth(rect)/3.5
let endAngle = CGFloat(2*M_PI)
CGContextAddArc(ctx, CGRectGetMidX(rect), CGRectGetMidY(rect), rad, 0, endAngle, 1)
CGContextSetFillColorWithColor(ctx,UIColor.grayColor().CGColor)
CGContextSetStrokeColorWithColor(ctx,UIColor.whiteColor().CGColor)
CGContextSetLineWidth(ctx, 4.0)
// use to fill and stroke path (see http://stackoverflow.com/questions/13526046/cant-stroke-path-after-filling-it )
CGContextDrawPath(ctx, kCGPathFillStroke);
for i in 1...60 {
// save the original position and origin
CGContextSaveGState(ctx)
// make translation
CGContextTranslateCTM(ctx, CGRectGetMidX(rect), CGRectGetMidY(rect))
// make rotation
CGContextRotateCTM(ctx, degree2radian(CGFloat(i)*6))
if i % 5 == 0 {
// if an hour position we want a line slightly longer
drawSecondMarker(ctx: ctx, x: rad-15, y:0, radius:rad, color: UIColor.whiteColor())
}
else {
drawSecondMarker(ctx: ctx, x: rad-10, y:0, radius:rad, color: UIColor.whiteColor())
}
// restore state before next translation
CGContextRestoreGState(ctx)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment