您的位置:首页 > 其它

mac 动态获取文本文字的宽度和高度

2014-01-22 17:20 375 查看
// 1获取文字的基本信息存入字典

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                            [NSFont systemFontOfSize: [NSFont smallSystemFontSize]], NSFontAttributeName,
                            [NSParagraphStyle defaultParagraphStyle], NSParagraphStyleAttributeName,
                            nil];
NSSize size = NSMakeSize(200.0, MAXFLOAT);
NSRect bounds;

// 2获得该文字的高度和宽度
bounds = [@"This is a really really really really really really really long string that won't fit on one line"
             boundingRectWithSize: size
             options: NSStringDrawingUsesFontLeading
             attributes: attributes];

NSLog(@"height: %02f, width: %02f", bounds.size.height, bounds.size.width);

// mac 还有一个动态获取文本高度的方法,但是此方法算出的高度会有一定的误差。蛋疼
// 动态调整文字的高度
float heightForStringDrawing(NSString *myString, NSFont *myFont,float myWidth)
{
    //you instantiate the needed text objects and hook them together
    NSTextStorage *textStorage = [[[NSTextStorage alloc]
                                   initWithString:myString] autorelease];
    NSTextContainer *textContainer = [[[NSTextContainer alloc]
                                       initWithContainerSize: NSMakeSize(myWidth, FLT_MAX)] autorelease];
    NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init]
                                      autorelease];
    
    // Once the text objects are created, you can hook them together:
    [layoutManager addTextContainer:textContainer];
    [textStorage addLayoutManager:layoutManager];
    
    // Set the line fragment padding to 0 to get an accurate width measurement.
    [textStorage addAttribute:NSFontAttributeName value:myFont
                        range:NSMakeRange(0, [textStorage length])];
    
    [textContainer setLineFragmentPadding:0.0];
    
    (void) [layoutManager glyphRangeForTextContainer:textContainer];
    
    
    
    return [layoutManager usedRectForTextContainer:textContainer].size.height;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: