objective-c – 特定于帧宽的NSString字体大小
发布时间:2020-12-16 06:48:25 所属栏目:百科 来源:网络整理
导读:我使用drawRect进行文本显示,调用NSString.我试图使用sizeWithFont实现自动调整字体大小(缩小),默认字体大小为17,并使用循环将字体大小减小1,如果它不适合宽度的大小.任何人都可以帮我解决这个问题吗?现在示例很好我只是将字体大小设置为17.0 [[self.string
我使用drawRect进行文本显示,调用NSString.我试图使用sizeWithFont实现自动调整字体大小(缩小),默认字体大小为17,并使用循环将字体大小减小1,如果它不适合宽度的大小.任何人都可以帮我解决这个问题吗?现在示例很好我只是将字体大小设置为17.0
[[self.string displayName] drawAtPoint:CGPointMake(xcoord,ycoord) withFont:[UIFont boldSystemFontOfSize:17.0]]; CGSize size = [[self.patient displayName] sizeWithFont:[UIFont boldSystemFontOfSize:17.0]]; max_current_y = size.height > max_current_y ? size.height : max_current_y; xcoord = xcoord + 3.0f + size.width; 解决方法
好吧,那算了.这是使用NSString返回字体的相同方法的修改版本:
-(UIFont*)getFontForString:(NSString*)string toFitInRect:(CGRect)rect seedFont:(UIFont*)seedFont{ UIFont* returnFont = seedFont; CGSize stringSize = [string sizeWithAttributes:@{NSFontAttributeName : seedFont}]; while(stringSize.width > rect.size.width){ returnFont = [UIFont systemFontOfSize:returnFont.pointSize -1]; stringSize = [string sizeWithAttributes:@{NSFontAttributeName : returnFont}]; } return returnFont; } 以下是如何调用它: NSString* stringToDraw = @"Test 123"; CGRect rect = CGRectMake(100.,100.,200.); UIFont* font = [self getFontForString:stringToDraw toFitInRect:rect seedFont:[UIFont systemFontOfSize:20]]; [stringToDraw drawInRect:rect withFont:font]; 代码适用于iOS7 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |