Draw a pie chart with UIBezierPath

I'm trying to draw a PieChart using UIBezierPath, and I'm pretty close to that, however I have a problem, as you can see in the screenshot attached screenshot2 Here is the code I'm using:

-(void)drawRect:(CGRect)rect { CGRect bounds = self.bounds; CGPoint center = CGPointMake((bounds.size.width/2.0), (bounds.size.height/2.0)); NSManagedObject *gameObject = [SCGameManager sharedInstance].gameObject; int playerNumber = 0; int totalOfPlayers = [(NSSet*)[gameObject valueForKey:@"playerColors"] count]; float anglePerPlayer = M_PI*2 / totalOfPlayers; for (NSManagedObject *aPlayerColor in [gameObject valueForKey:@"playerColors"]){ //Draw the progress CGFloat startAngle = anglePerPlayer * playerNumber; CGFloat endAngle = startAngle + anglePerPlayer; UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:self.frame. size.width/2 startAngle:startAngle endAngle:endAngle clockwise:YES]; UIColor *playerColor = [SCConstants getUIColorForPlayer:[[aPlayerColor valueForKey:@"colorIndex"] intValue]]; [playerColor set]; [path fill]; playerNumber++; } } 

Apparently, I just need to move my path to the center of the circle and then close it, but when I add the following line of code:

 [path addLineToPoint:self.center]; [path closePath]; 

He is drawing something strange: screenshot1

Do you have any idea what is going on with my code? I'm not a Bezier expert at all, so any help is appreciated!

Thanks!

+4
source share
1 answer

It seems that the center point you are using is the problem. Indeed, if you look at the documentation for the center property of the UIView, you will find:

The center is defined in the coordinate system of its supervisor and is measured in points.

You want the center point of the view to be indicated in its own coordinate system, and not in its supervision. You have already defined the view center in your own coordinates:

 CGPoint center = CGPointMake((bounds.size.width/2.0), (bounds.size.height/2.0)); 

So, just change the point you use as the center point from self.center to center , for example:

 [path addLineToPoint:center]; 
+9
source

All Articles