objective-c - NSString 字体大小特定于框架宽度

标签 objective-c nsstring drawrect sizewithfont

我正在使用 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/

相关文章:

ios - 将 NSString 转换为 Cocos2d-x CCString

objective-c - setNeedsDisplay 不会按预期触发 subview 中的 drawRect

ios - 画不出直线

iOS 自定义 UIView 绘图 - CAShapeLayers 或 drawRect?

ios - 我可以合并/修改通知栏中的通知吗?

ios - 覆盖 canBecomeFirstResponder 导致 viewController 崩溃

objective-c - -forwardInvocation 用于类方法

objective-c - 获取行开头的空格数

ios - 画一个长方形,一边切圆弧

objective-c - 如何将 sizeWithFont 转换为 sizeWithAttributes(iOS 7)