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

时间:2015-05-25 18:42:08

标签: 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]];

1 个答案:

答案 0 :(得分:2)

核心文本解决方案(注意,如果需要,maxWidth允许换行):

SHA1