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

标签 macos height width

计算固定 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]];

最佳答案

核心文本解决方案(注意,如果需要,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);
}

关于macos - 根据xcode中的文本、字体、文本颜色计算高度和宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30444290/

相关文章:

javascript - JavaScript 中的自动换行检测

ios - 我在理解如何使用自动布局的逻辑时遇到问题

javascript - 使用 JavaScript/jQuery 调整图像大小

macos - 通过brew在MacOS X上安装Wireshark

cocoa - 检测应用程序正在使用什么框架

ios - 咕噜声/PhoneGap : Warning: stdout maxBuffer exceeded

html - 如何让父div适应 child 的大小

css - 如何使菜单的宽度等于所有列表项的宽度

html - 图片不在正确的位置[HTML/CSS]

Qt 中的 cocoa 纹理窗口