2015-05-25 4 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

Параметр width - это предложение CTTypesetterSuggestLineBreak для максимальной ширины, которой должен обладать текст. Затем он возвращает длину, основанную на разбиении (обертке) строки так, чтобы она соответствовала предоставленной ширине. – geowar

+0

Привет, я решил свою проблему. Я получал ширину от 'NSCell cellSize', вместо размера, возвращаемого' titleRectForBounds: '. – Sheamus

Смежные вопросы