使用CGSize ... sizeWithAttributes的CGRect的确切大小

时间:2015-03-01 14:54:02

标签: objective-c cgrect cgsize

下面的代码是我在制作pdf文档时如何使用CGRect绘制一些文字的示例。我需要计算使用 comment1 绘制的CGRect的确切大小,以便 comment2 comment3 等所有内容都启动在页面上的正确位置。

变量 currentLine 会跟踪页面上CGRect的结尾位置。它适用于简短评论,但不适用于后续评论重叠的长评论。字体和字体大小都是正确的。

textRect = CGRectMake(60, currentLine, 650, 300);
myString =  self.comments1.text;
[myString drawInRect:textRect withAttributes:_textAttributesNotBold ];

CGSize contentSize = [myString sizeWithAttributes: @{NSFontAttributeName: [UIFont fontWithName:@"Arial" size:12]}];
currentLine =  currentLine +  contentSize.height;

我想知道问题是CGRectMake是否使用650宽度。 CGSize .... sizeWithAttributes似乎没有考虑到这一点。计算 contentSize.height CGSize .... sizeWithAttributes假设的宽度是多少?

或者有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

我不确定这是否是一种好方法,但似乎有效:

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"Arial" size:12]};
CGRect rect = [comment1.text boundingRectWithSize:CGSizeMake(650, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];

CGRect textRect = CGRectMake(60, currentLine, 650, rect.size.height);
[comment1.text drawInRect:textRect withAttributes:attributes ];
currentLine =  currentLine +  rect.size.height;
相关问题