如果我错了,请纠正我。
我尝试使用 Core Text 计算出字符的确切边界矩形。但是我收到的高度总是大于屏幕上绘制字符的实际高度。在这种情况下,实际高度在 20 左右,但无论如何该函数只给我 46。
任何人都可以对此有所了解吗?
谢谢。
这是代码
- (void)viewDidLoad{
[super viewDidLoad];
NSString *testString = @"A";
NSAttributedString *textString = [[NSAttributedString alloc] initWithString:testString attributes:@{
NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:40]
}];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:textString];
NSLayoutManager *textLayout = [[NSLayoutManager alloc] init];
// Add layout manager to text storage object
[textStorage addLayoutManager:textLayout];
// Create a text container
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.view.bounds.size];
// Add text container to text layout manager
[textLayout addTextContainer:textContainer];
NSRange range = NSMakeRange (0, testString.length);
CGRect boundingBox = [textLayout boundingRectForGlyphRange:range inTextContainer:textContainer];
//BoundingBox:{{5, 0}, {26.679688, 46}}
// Instantiate UITextView object using the text container
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20,20,self.view.bounds.size.width-20,self.view.bounds.size.height-20)
textContainer:textContainer];
// Add text view to the main view of the view controler
[self.view addSubview:textView];
}