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; }
相关文章推荐
- IOS动态获取文本的高度--自适应文本宽度、高度Textview
- IOS动态获取字符串NSString的长宽--自适应文本宽度、高度
- 动态获取字符串 NSString的长宽--------自适应文本宽度、高度
- 动态获取字符串 NSString的长宽--------自适应文本宽度、高度
- 动态的获取label文本的宽度和高度,来判断是不是需要折行显示
- JS动态获取浏览器宽度和高度
- Win 8 app 获取窗口的宽度和高度, 本地化, 及文本读取
- 获取屏幕的宽度以及动态设置ImageView的宽度、高度
- iPhone:动态获取UILabel的高度和宽度
- 如何使用代码动态的获取和设置ImageView的宽度和高度?
- ios动态获取UILabel的高度和宽度
- Android下动态获取View的高度或宽度
- [Flex] 动态获取组件宽度和高度
- GDI 与 GDIPlus 获取文字宽度和高度的方法
- MeasureString 通过文本宽度获取绘制高度
- ios动态获取UILabel的高度和宽度
- iPhone:动态获取UILabel的高度和宽度
- js动态获取图片的宽度和高度像素值
- iPhone:动态获取UILabel的高度和宽度
- iOS 重写UITableViewCell之动态获取label文字的宽度进行布局