I'm trying to draw a PieChart using UIBezierPath, and I'm pretty close to do so, however, I've got a problem, as you can see on the screenshot attached Here's 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'm adding the following line of code :
[path addLineToPoint:self.center];
[path closePath];
It draws something weird :
Do you have any idea of what is going wrong with my code? I'm not a Bezier expert at all, so any help is welcome!
Thanks!
It looks like the center point you're using is the problem. Indeed, if you look at the documentation for the center
property of UIView, you'll find:
The center is specified within the coordinate system of its superview and is measured in points.
You want the center point of the view specified in its own coordinate system, not that of its superview. You've already determined the center of the view in its own coordinates here:
CGPoint center = CGPointMake((bounds.size.width/2.0), (bounds.size.height/2.0));
So just change the point you're using as the center point from self.center
to center
, like this:
[path addLineToPoint:center];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With