我正在使用 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., 100., 200.);
UIFont* font = [self getFontForString:stringToDraw toFitInRect:rect seedFont:[UIFont systemFontOfSize:20]];
[stringToDraw drawInRect:rect withFont:font];
代码适用于 iOS7+
关于objective-c - NSString 字体大小特定于框架宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14818189/