计算NSString文本内容的高度

本文介绍了在iOS中如何计算NSString文本内容的高度。在IOS7之前,可以使用`sizeWithFont:constrainedToSize:`方法;而在IOS7及之后,推荐使用`boundingRectWithSize:options:attributes:context:`来获取文本的高度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IOS7 之前的方法

           - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

       参数: font : 字体

                 size : 大小

       return : CGSize类型  根据返回CGSize对象就可以得到 height   

    IOS 7 下方法:

    - (CGRect)boundingRectWithSize:(CGSize)size 

                           options:(NSStringDrawingOptions)

                                 optionsattributes:(NSDictionary *)attributes

                           context:(NSStringDrawingContext *)context

     

Parameters
size

The size of the rectangle to draw in.

options

String drawing options.

attributes

A dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an NSAttributedString object, but in the case of NSString objects, the attributes apply to the entire string, rather than ranges within the string.

context

The string drawing context to use for the receiver, specifying minimum scale factor and tracking adjustments.

Return Value

The bounding rect for the receiver drawn using the given options and display characteristics. The rect origin returned from this method is the first glyph origin.



String Drawing Options

Options for customizing the way strings are drawn.

enum {
   NSStringDrawingTruncatesLastVisibleLine = 1 << 5,
   NSStringDrawingUsesLineFragmentOrigin = 1 << 0,
   NSStringDrawingUsesFontLeading = 1 << 1,
   NSStringDrawingUsesDeviceMetrics = 1 << 3,
};
typedef NSInteger NSStringDrawingOptions;
NSStringDrawingTruncatesLastVisibleLine

Truncate and add an ellipsis character to the last visible line if the text does not fit into the specified bounds. This option is ignored if theNSStringDrawingUsesLineFragmentOrigin option is not also specified.

NSStringDrawingUsesLineFragmentOrigin

The origin specified when drawing the string is the line fragment origin and not the baseline origin.

NSStringDrawingUsesFontLeading

Use the font leading information to calculate line heights.

NSStringDrawingUsesDeviceMetrics

Use the image glyph bounds (instead of the typographic bounds) when computing layout.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值