Recently I was looking for a way to draw pie charts (you know, the one with an 'exploded' slice) on my Macbook.

Unfortunealy I didn't find much on the Internet, so I've started to experiment a bit myselfs.

The following code draws a pie chart with one slice exploded from the other :

The trick is that you draw an imaginary circle around the center, on this circle is the center of the 'exploded' slice.

#define PI 3.14159265358979323846

NSBezierPath *greenPath = [NSBezierPath bezierPath] ;

// set some line width

[greenPath setLineWidth: 2 ] ;

// move to the center so that we have a closed slice

// size_x and size_y are the height and width of the view

[greenPath moveToPoint: NSMakePoint( size_x/2, size_y/2 ) ] ;

// draw an arc (perc is a certain percentage ; something between 0 and 1

[greenPath appendBezierPathWithArcWithCenter:NSMakePoint( size_x/2, size_y/2) radius:50 startAngle:0 endAngle: 360 * perc ] ;

// close the slice , by drawing a line to the center

[greenPath lineToPoint: NSMakePoint(size_x/2, size_y/2) ] ;

[greenPath stroke] ;

[[NSColor greenColor] set] ;

// and fill it

[greenPath fill] ;

greenPath = [NSBezierPath bezierPath] ;

[[NSColor blackColor] set] ;

[greenPath setLineWidth: 2 ] ;

// draw the second slice, now exploded from the original center

// so to get it exploded I move (10,7) points from the original center

// but on the imaginary circle (thats why the cos and the sin)

// note mide_angle is the angle halve way from the arc, you can experiment with multiple

// angles, note also that the angle is in degrees

[greenPath moveToPoint: NSMakePoint(size_x/2 - 10 * cos ( PI * mid_angle / 180 ) , size_y/2 - 7 * sin ( PI * mid_angle / 180 )) ] ;

// and now draw the other slice

[greenPath appendBezierPathWithArcWithCenter:NSMakePoint( size_x/2 - 10 * cos ( PI * mid_angle / 180 ) , size_y/2 - 7 * sin ( PI * mid_angle / 180 )) radius:50 startAngle:360 * perc endAngle:360 ] ;

// close the slice

[greenPath lineToPoint: NSMakePoint( size_x/2 - 10 * cos ( PI * mid_angle / 180 ) , size_y/2 - 7 * sin ( PI * mid_angle / 180 ) ) ] ;

[greenPath stroke] ;

[[NSColor blueColor] set] ;

[greenPath fill] ;

The result of above code is here :

Next time I'll add some code to add text to the slices

Trump campaign launches streaming Facebook show

26 minutes ago

## No comments:

## Post a Comment