遇到了一个需求,就是在已完成的饼图中嵌入文字或者数字,文字或者数字的大小需要根据饼图圆形的半径自适应大小。查看了一些资料没有找到想要的东西,就自己写了。。。
上代码吧。。。
NSString *str = @"文本";
//设置段落格式
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingMiddle;
/// Set text alignment
paragraphStyle.alignment = NSTextAlignmentCenter;
//提前给定一个字体的大小并作为一个局部变量,计算出文字或数字的size大小
float currentFontSize=22.0f;
CGSize boudingSize = CGSizeMake(300, 300);
CGSize requiredSize = CGSizeZero;
UIFont * founda = [UIFont systemFontOfSize:currentFontSize];
NSDictionary *dic = @{NSFontAttributeName:founda,NSParagraphStyleAttributeName: paragraphStyle};
requiredSize = [str boundingRectWithSize:boudingSize options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
//当算出的宽度大于圆形直径时,这时文本就显示不全了,使用while循环改变字体的大小
//inner_circle_radius 圆形半径
if (requiredSize.width>2*inner_circle_radius) {
while (requiredSize.width>(2*inner_circle_radius1)) {
currentFontSize--;
requiredSize=[str boundingRectWithSize:boudingSize options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:[UIFont systemFontOfSize:currentFontSize],
NSParagraphStyleAttributeName: paragraphStyle} context:nil].size;
}
}
//将文本画出
[str drawInRect:CGRectMake(origin_x-inner_circle_radius1, origin_y-requiredSize.height+10, 2*inner_circle_radius1, requiredSize.height) withAttributes:@{NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:[UIFont systemFontOfSize:currentFontSize],
NSParagraphStyleAttributeName: paragraphStyle}];
}
这样就完美解决了。。。