Reputation: 459
I have Created a PieChart Using the following Code. Here, I Have taken the sum of x
and y
as 100% to display the x%
as red color and y%
as green color on pieChart.
On the red color i want to display the exact x%
(Example 45%
(or) 55%
) and on the green color i want to display the exact y%
(Example 55%
(or) 45%
).
In my application the X
and Y
values are Variables. Those Values are changing each time when i run my application. I want to display the pieChart with green and red colors with the percentage on those regions. How Can i make frames to display percentages on that regions?
.m file
- (void)drawRect:(CGRect)rect
{
// Drawing code
int x = 25;
int y = 42;
float sum = x + y;
float mult = (360/sum);
float startDeg = 0;
float endDeg = 0;
int x = 74;
int y = 60;
int r = 60;
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 1.0, 1.0, 1.0, 1.0);
CGContextSetLineWidth(ctx, 2.0);
startDeg = 0;
endDeg = (x * mult);
if(startDeg != endDeg)
{
CGContextSetRGBFillColor(ctx, 0.0, 0.8, 0.0, 1.0);
CGContextMoveToPoint(ctx, x, y);
CGContextAddArc(ctx, x, y, r, (startDeg)*M_PI/180.0, (endDeg)*M_PI/180.0, 0);
CGContextClosePath(ctx);
CGContextFillPath(ctx);
}
startDeg = endDeg;
endDeg = endDeg + (y * mult);
if(startDeg != endDeg)
{
CGContextSetRGBFillColor(ctx, 0.8, 0.0, 0.0, 1.0);
CGContextMoveToPoint(ctx, x, y);
CGContextAddArc(ctx, x, y, r, (startDeg)*M_PI/180.0, (endDeg)*M_PI/180.0, 0);
CGContextClosePath(ctx);
CGContextFillPath(ctx);
}
}
Upvotes: 2
Views: 2218
Reputation: 6710
You can draw a string with NSString drawInRect during the drawRect method. For example:
[percentageString drawInRect:CGRectMake(100, 100, 30, 20)
withFont:font
lineBreakMode:UILineBreakModeClip
alignment:UITextAlignmentLeft];
Update
Here is how to find the x, y for placing text:
CGFloat startDegree = 180; // start at 180
CGFloat endDegree = degree; // end at some value
CGFloat mid = (endDegree + startDegree) / 2; // find midpoint
CGFloat rad = DEGREES_TO_RADIANS(mid); // convert to radians
// center is center of pie chart
// radius is how big the pie chart is
// 30 is extra to draw text outside circle
CGFloat x = center.x + ((radius + 30) * cos(rad));
CGFloat y = center.y + ((radius + 30) * sin(rad));
NSLog(@"X Y: %f %f %f", x, y, degree);
NSString *text = @"Test";
[text drawInRect:CGRectMake(x, y, 50, 44) withFont:[UIFont systemFontOfSize:14.0f]];
I had a sample pie chart so I used that. It has a slider with degrees. In the example, I can draw a segment of the pie chart from 180 degrees to 360 degrees.
Upvotes: 4