//可以看到是用寬度直接判斷高度忆嗜,對字體大小直接--己儒,實際上還能優(yōu)化用寬度去適配。如果在即時顯示效果上可能會有點卡頓捆毫,建議在手勢結(jié)束闪湾。或者單次ui實現(xiàn)中判斷绩卤。當(dāng)然途样,略微的卡頓延遲還是能完全接受的江醇。
- (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;
}