根据 xcode 中的文本、字体、文本颜色计算高度和宽度

calculate height and width based on text , font , text color in xcode

计算固定 UIView 中文本字段(包括自动换行等)的正确高度和宽度(格式化文本,包括文本大小、文本颜色、文本字体)的最佳方法是什么

下图中文字没有右对齐Check the Image

下图中的文字显示不正确check the image

我正在使用以下代码计算图像的高度和宽度

    NSString* text=[textField stringValue];
    NSDictionary *attributes;
    NSTextView* textView =[[NSTextView alloc] init];
    [textView setString:text];

    attributes = @{NSFontAttributeName : [NSFont fontWithName:fontName size:fontValue], NSForegroundColorAttributeName : [NSColor colorWithCalibratedRed:redValueTextColor green:GreenValueTextColor blue:blueValueTextColor alpha:1], NSBackgroundColorAttributeName : [NSColor colorWithCalibratedRed:redValueTextBackgroundColor green:GreenValueTextBackgroundColor blue:blueValueTextBackgroundColor alpha:1]};
textView.backgroundColor=[NSColor colorWithCalibratedRed:redValueTextBackgroundColor green:GreenValueTextBackgroundColor blue:blueValueTextBackgroundColor alpha:1];

    NSInteger maxWidth  = 600;
    NSInteger maxHeight = 20000;
    CGSize constraint   = CGSizeMake(maxWidth, maxHeight);
    NSRect newBounds    = [text boundingRectWithSize:constraint options:NSLineBreakByCharWrapping|NSStringDrawingUsesFontLeading attributes:attributes];

    textView.frame = NSMakeRect(textView.frame.origin.x, textView.frame.origin.y, newBounds.size.width, newBounds.size.height);
    textView =[NSColor colorWithCalibratedRed:redValueTextColor green:GreenValueTextColor blue:blueValueTextColor alpha:1];
    [textView setFont:[NSFont fontWithName:fontName size:fontValue]];

Core Text 解决方案(注意,如果需要,maxWidth 允许换行):

(CGSize)sizeForText:(NSAttributedString *)string maxWidth:(CGFloat)width
{
    CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedString((__bridge CFAttributedStringRef)string);

    CFIndex offset = 0, length;
    CGFloat y = 0, lineHeight;
    do {
        length = CTTypesetterSuggestLineBreak(typesetter, offset, width);
        CTLineRef line = CTTypesetterCreateLine(typesetter, CFRangeMake(offset, length));

        CGFloat ascent, descent, leading;
        CTLineGetTypographicBounds(line, &ascent, &descent, &leading);

        CFRelease(line);

        offset += length;

        ascent = roundf(ascent);
        descent = roundf(descent);
        leading = roundf(leading);

        lineHeight = ascent + descent + leading;
        lineHeight = lineHeight + ((leading > 0) ? 0 : roundf(0.2*lineHeight)); //add 20% space

        y += lineHeight;

    } while (offset < [string length]);

    CFRelease(typesetter);

    return CGSizeMake(width, y);
}