Created
February 15, 2016 16:39
-
-
Save sketchytech/2a69ad937b4995af40a7 to your computer and use it in GitHub Desktop.
Simple pie chart drawing code for iOS using CAShapeLayer and UIBezierPath
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
extension CGFloat { | |
func radians() -> CGFloat { | |
let b = CGFloat(M_PI) * (self/180) | |
return b | |
} | |
} | |
extension UIBezierPath { | |
convenience init(circleSegmentCenter center:CGPoint, radius:CGFloat, startAngle:CGFloat, endAngle:CGFloat) | |
{ | |
self.init() | |
self.moveToPoint(CGPointMake(center.x, center.y)) | |
self.addArcWithCenter(center, radius:radius, startAngle:startAngle.radians(), endAngle: endAngle.radians(), clockwise:true) | |
self.closePath() | |
} | |
} | |
func pieChart(pieces:[(UIBezierPath, UIColor)], viewRect:CGRect) -> UIView { | |
var layers = [CAShapeLayer]() | |
for p in pieces { | |
let layer = CAShapeLayer() | |
layer.path = p.0.CGPath | |
layer.fillColor = p.1.CGColor | |
layer.strokeColor = UIColor.whiteColor().CGColor | |
layers.append(layer) | |
} | |
let view = UIView(frame: viewRect) | |
for l in layers { | |
view.layer.addSublayer(l) | |
} | |
return view | |
} | |
let rectSize = CGRectMake(0,0,400,400) | |
let centrePointOfChart = CGPointMake(CGRectGetMidX(rectSize),CGRectGetMidY(rectSize)) | |
let radius:CGFloat = 100 | |
let piePieces = [(UIBezierPath(circleSegmentCenter: centrePointOfChart, radius: radius, startAngle: 250, endAngle: 360),UIColor.brownColor()), (UIBezierPath(circleSegmentCenter: centrePointOfChart, radius: radius, startAngle: 0, endAngle: 200),UIColor.orangeColor()), (UIBezierPath(circleSegmentCenter: centrePointOfChart, radius: radius, startAngle: 200, endAngle: 250),UIColor.lightGrayColor())] | |
pieChart(piePieces, viewRect: CGRectMake(0,0,400,400)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
Anyone knows how to convert these code to objective-c?