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



// 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值