//可以看到是用宽度直接判断高度,对字体大小直接--,实际上还能优化用宽度去适配。如果在即时显示效果上可能会有点卡顿,建议在手势结束。或者单次ui实现中判断。当然,略微的卡顿延迟还是能完全接受的。
- (int)calculationSize:(float)width height:(float)height text:(NSString *)text{
int fontSize ;
if (width>height) {
fontSize = (int)height;
}else{
fontSize = (int)width;
}
int count = fontSize;
CGSize testSize = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont fontWithName:_fontName size:fontSize]} context:nil].size;
for (int i = 0; i<count; i++) {
if (testSize.height>height) {
fontSize--;
testSize = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont fontWithName:_fontName size:fontSize]} context:nil].size;
}else{
break;
}
NSLog(@"%d",fontSize);
NSLog(@"%f,%f",testSize.width,testSize.height);
}
return fontSize;
}