How to use NSString sizeWithFont and drawInRect to train how many lines to draw

I draw several “pages” of images using CGContext in iOS. I have widely used combinations of sizeWithFont and drawInRect in my application. What I need to do is split a large piece of text across multiple pages. I can evaluate it and decide if he needs another page, but how do I know where to cut it? Do I have to do an ugly loop to check word by word until I find a line that is perfect for the page and then cut the line at that point? Is there a smarter way?

Any ideas?

Thank.

+3
source share
2 answers

NSString UIKit , , . , .

sizeWithFont:constrainedToSize:lineBreakMode:

, , CGSize , , . , .

CGSize maximumSize = CGSizeMake(pageWidth, 999999999);
CGSize expectedSize = [veryLongString sizeWithFont:theFont constrainedToSize:maximumSize lineBreakMode:theLineBreakMode];

expectedSize , , ( ). , .

NSInteger totalPages = ceil(expectedSize.height / heightOfOnePage);

, , . . , 300px, 16px, 300/16 = 18.75, .

NSInteger linesWithoutClipping = floor(initialPageHeight / theFont.lineHeight);
CGFloat optimalPageHeight = linesWithoutClipping * theFont.lineHeight;

18 16, 288, .

, lineHeight iOS 4.0, , .

+6

, .

NSArray * paragraphs = [text componentsSeparatedByString:@"\n"];

, , .

+2

Source: https://habr.com/ru/post/1791405/


All Articles