问题描述
我使用以下代码创建了一个PieChart。在这里,我已经将 x
和 y
的总和作为100%显示 x %
为红色, y%
为pieChart上的绿色。
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.
在红色上我想显示确切的 x%
(示例 45%
(或) 55%
)在绿色上我想显示确切的 y%
(示例 55%
(或) 45%
)。
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%
).
在我的应用程序中, X
和 Y
的值是变量。每次运行我的应用程序时,这些值都在变化。我想用绿色和红色显示带有这些区域百分比的pieChart。如何制作框架以显示该区域的百分比?
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文件
- (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);
}
}
推荐答案
你可以在drawRect方法中使用NSString drawInRect绘制一个字符串。例如:
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];
更新
以下是如何找到放置文本的x,y:
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]];
我有一个样本饼图所以我用过它。它有一个度数滑块。在这个例子中,我可以将饼图的一段从180度绘制到360度。
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.
这篇关于如何在PieChart上显示文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!