如果我错了,请纠正我。
我尝试使用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];
}
答案 0 :(得分:0)
我目前正在为Core Text渲染工作,并且对这类信息没有直接提供感到惊讶(对于相关的图形,如合适的背景/轮廓)
这些都是正在进行的其他stackoverflow问题和我自己的测试,以获得完美的边界框(紧)
常用字体属性
let leading = floor( CTFontGetLeading(fontCT) + 0.5)
let ascent = floor( CTFontGetAscent(fontCT) + 0.5)
let descent = floor( CTFontGetDescent(fontCT) + 0.5)
var lineHeight = ascent + descent + leading
var ascenderDelta = CGFloat(0)
if leading > 0 {
ascenderDelta = 0
}
else {
ascenderDelta = floor( 0.2 * lineHeight + 0.5 )
}
lineHeight = lineHeight + ascenderDelta
对于段落样式
var para = NSMutableAttributedString()
// append attributed strings and set NSMutableParagraphStyle
/* ... */
let options : NSStringDrawingOptions = .UsesFontLeading | .UsesLineFragmentOrigin | .UsesDeviceMetrics
let rect = para.boundingRectWithSize(CGSizeMake(fontBoxWidth,10000), options: options, context: nil)
var backgroundBounds = CGRectMake(boundingBox.origin.x + point.x, boundingBox.origin.y + point.y + lineHeight, boundingBox.width, boundingBox.height + ascenderDelta)
对于CTFrames
let lines = CTFrameGetLines(frame) as NSArray
let numLines = CFArrayGetCount(lines)
for var index = 0; index < numLines; index++ {
var ascent = CGFloat(0),
descent = CGFloat(0),
leading = CGFloat(0),
width = CGFloat(0)
let line = lines[index] as! CTLine
width = CGFloat(CTLineGetTypographicBounds(line, &ascent, &descent, &leading))
// adjust with common font property code
var lineOrigin : CGPoint = CGPointMake(0,0)
CTFrameGetLineOrigins(frame, CFRangeMake(index, 1), &lineOrigin)
let bounds = CGRectMake(point.x + lineOrigin.x, point.y + lineOrigin.y - descent, width, ascent + descent)