【问题标题】:The exact size of a CGRect using CGSize ... sizeWithAttributes使用 CGSize ... sizeWithAttributes 的 CGRect 的确切大小
【发布时间】:2015-03-01 14:54:01
【问题描述】:

下面的代码是我在制作 pdf 文档时如何使用CGRect 绘制一些文本的示例。我需要计算使用 comment1 绘制的 CGRect 的确切大小,以便 comment2comment3 等都从页面上的正确位置。

变量currentLine 跟踪CGRect 的末尾在页面上的位置。它适用于短 cmets,但不适用于后续 cmets 重叠的长 cmets。字体和字号都正确。

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;

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

或者有更好的方法吗?

【问题讨论】:

  • 我认为你这样做是向后的......你为什么不先计算内容大小......然后创建一个具有该大小的矩形......然后在 中绘制字符串那 对吗?然后......你为什么不将 withAttributes: 的相同参数传递给计算大小的方法,就像你传递给实际绘图的方法一样?
  • 有道理,但问题还是一样。 contentSize.height 由 sizeWithAttributes: 计算得出,但不考虑 CGRectMake 的宽度。我不明白它是如何在不知道框架宽度的情况下计算高度的。
  • @nhgrif 有帮助 - 谢谢。我似乎找到了解决方案(在此处添加),但对我来说似乎有点混乱。虽然有效。

标签: objective-c cgrect cgsize


【解决方案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;

【讨论】:

  • 您应该在两个要求文本属性的地方使用attributes 变量。最后一行可能很简单:currentLine += rect.size.height;
猜你喜欢
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
  • 2012-08-17
  • 2014-07-15
  • 1970-01-01
相关资源
最近更新 更多