0

The code below is an example of how I use CGRect to draw some text when making a pdf document. I need to calculate the exact size of the CGRect being drawn with comment1 so that the ones for comment2, comment3 etc all start in the right place on the page.

The variable currentLine keeps track of where the end of the CGRect is on the page. It works fine for short comments but not long comments where subsequent comments overlap. The font and font size are correct.

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;

I wonder if the problem is with the CGRectMake using a 650 width. This does not seem to be taken into account in the CGSize .... sizeWithAttributes. What width does the CGSize .... sizeWithAttributes assume when calculating the contentSize.height?

Or is there a better way of doing this?

RGriffiths
  • 5,722
  • 18
  • 72
  • 120
  • I think you're doing this backward... why don't you calculate the content size first... then create a rect with that size... then draw the string in *that* rect? And then... how come you're not passing the same arguments for `withAttributes:` to the method for calculating the size as you are to the method for actually drawing? – nhgrif Mar 01 '15 at 15:18
  • That makes sense but the problem is still the same. contentSize.height is calculated from sizeWithAttributes: but takes no account of the width of the CGRectMake. I don't understand how it calculates the height without knowing the width of the frame. – RGriffiths Mar 01 '15 at 15:22
  • 1
    possible duplicate of [iOS 7 sizeWithAttributes: replacement for sizeWithFont:constrainedToSize](http://stackoverflow.com/questions/19145078/ios-7-sizewithattributes-replacement-for-sizewithfontconstrainedtosize) – nhgrif Mar 01 '15 at 15:25
  • @nhgrif Helpful - thanks. I have seemed to come to a solution (added here) but seems a bit messy to me. Works though. – RGriffiths Mar 01 '15 at 19:37

1 Answers1

1

I am not sure if this is a good way to do it but it seems to work:

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;
RGriffiths
  • 5,722
  • 18
  • 72
  • 120
  • You should use the `attributes` variable in both places that ask for text attributes. And the last line could be simply: `currentLine += rect.size.height;` – nhgrif Mar 01 '15 at 19:38