1

我正在创建一个 pdf 报告,它根据一系列UITextFields 中的文本呈现帧。目前我正在使用以下一系列方法。这些变量用于跟踪下一帧的位置,并基于当前UITextField考虑的文本长度以及渲染时每行的长度在 pdf doc 上约为 97 个字符的假设。

-(void) drawTextObservationComment;
{
//pdfLineHeight is the height of size 12 rendered text
pdfLineHeight = 15;
CGContextRef summaryContext = UIGraphicsGetCurrentContext();
UIFont *font = [UIFont fontWithName:@"arial" size:12];
CGContextSetFillColorWithColor (summaryContext, [UIColor blackColor].CGColor);

//pdfCurrentLine is the y-axis coordinate from which to begin the new frame
CGRect textRect = CGRectMake(60, pdfCurrentLine, 650, 300);
NSString *myString =  self.observationComment.text;
[myString drawInRect:textRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];

//checks for the no of carriage returns within the text field
NSInteger numberOfLines = [[myString componentsSeparatedByString:@"\n"] count];

//the new pdfCurrentLine value is the previous value 
// + the no of new lines based on text length
// + the no lines based on the no of carriage returns within text field
// + 40 as standard gap
pdfCurrentLine =  pdfCurrentLine + (([observationComment.text length]/97)*pdfLineHeight) + ((numberOfLines - 1) * pdfLineWidth) + 40;
}

这在一定程度上有效,但我意识到它并不完全准确。帧中呈现的文本CGRect通常不是 97 个字符(尽管它通常在这个数字上下 10 个字符)。这取决于输入的文本(例如,字母“i”更细,因此在有很多“i”的行上可能有更多字符)。

我想知道是否有任何方法可以准确计算渲染文本实际使用的行数,从而使我能够准确计算下一帧的确切位置。或感激地收到任何其他建议。

4

1 回答 1

1

你看过NSString UIKit Additions的文档吗?

那里有一些方法可以返回渲染文本的大小,例如sizeWithFont:constrainedToSizesizeWithFont:constrainedToSize:lineBreakMode:

于 2013-05-23T22:46:27.697 回答