2015-05-25 37 views
2

什么是计算(包括文本大小,文本颜色,文本字体的格式化文本)固定UIView中文本字段的适当高度和宽度的最佳方式,包括字包裹等根据xcode中的文本,字体和文本颜色计算高度和宽度

在以下图像文本

不右对齐在下面的图像文本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]]; 
+0

这将是奇怪的,如果颜色影响的文字大小。 :) – rmaddy

+0

我不知道,但它是 – IOSDeveloper

回答

2

核心文本解决方案(注意,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); 
} 
+0

对我来说,CTTypesetterSuggestLineBreak返回整个字符串的长度。我错过了什么吗? – Sheamus

+0

宽度参数是CTTypesetterSuggestLineBreak对于文本的最大宽度的建议。然后它返回一个基于打破(包装)字符串的长度,以便它符合所提供的宽度。 – geowar

+0

嗨,我解决了我的问题。我从'NSCell cellSize'获取宽度,而不是'titleRectForBounds:'返回的大小。 – Sheamus

相关问题