好吧,我使用的是来自github Astrokin Piechart
的PieChart但是在这个饼图标签中没有添加到不同的切片中,我想要的东西如下所示
我已经查看了stackoverflow并且我正在尝试在绘制rect中绘制文本但似乎没有用。代码在下面
for (int i = 0; i < slicesCount; i++)
{
double value = [self.datasource pieChartView:self valueForSliceAtIndex:i];
NSString *title = [self.datasource pieChartView:self titleForSliceAtIndex:i];
endAngle = startAngle + M_PI*2*value/sum;
/*CGFloat x = centerX + (radius+10) * (cos((startAngle-90)*M_PI/180.0) + cos((endAngle-90)*M_PI/180.0)) / 2;
CGFloat y = centerY + (radius+10) * (sin((startAngle-90)*M_PI/180.0) + sin((endAngle-90)*M_PI/180.0)) / 2;
[title drawAtPoint:CGPointMake(x, y) withFont:[UIFont fontWithName:FONT_HELVETICA size:12.0]];*/
CGFloat x = centerX + ((radius + 10) * cos(startAngle));
CGFloat y = centerY + ((radius + 10) * sin(endAngle));
// NSLog(@"X Y: %f %f %f", x, y, degree);
NSString *text = @"Test";
[text drawInRect:CGRectMake(x, y, 50, 44) withFont:[UIFont systemFontOfSize:14.0f]];
CGContextAddArc(context, centerX, centerY, radius, startAngle, endAngle, false);
UIColor *drawColor = [self.datasource pieChartView:self colorForSliceAtIndex:i];
CGContextSetStrokeColorWithColor(context, drawColor.CGColor);
CGContextSetLineWidth(context, lineWidth);
CGContextStrokePath(context);
startAngle += M_PI*2*value/sum;
}
现在它看起来像这样
我可能做错了什么?
答案 0 :(得分:0)
您使用
绘制文字[text drawInRect:CGRectMake(x, y, 50, 44) withFont:[UIFont systemFontOfSize:14.0f]];
这使您的文字的左上角出现在点(x,y)。我可以看到,你希望文本的中心出现在点(x,y)。您需要做的是从x中减去文本宽度的一半,并为y减去相同的宽度,以便它变为:
CGFloat height = 50.0;
CGFloat width = 44.0;
[text drawInRect:CGRectMake(x - width / 2.0, y - height / 2.0, width, height) withFont:[UIFont systemFontOfSize:14.0f]];
此外,您还需要根据您拥有的字符串动态获取文字的宽度,&#34; 95%&#34;超过&#34; 5%&#34;是吗?所以你需要这样的东西:
UIFont *font = [UIFont systemFontOfSize:14.0f];
CGSize textSize = [text sizeWithFont:font]; // -sizeWithFont is deprecated in iOS7, you'll need something else
CGFloat height = textSize.height;
CGFloat width = textSize.width;
[text drawInRect:CGRectMake(x - width / 2.0, y - height / 2.0, width, height) withFont:font];