开发者

Core Text: counting pages in background thread

Let's say I'm writing text viewer for the iPhone using Core Text. Every time user changes base font size I need to count how many pages (fixed size CGRects) are needed to display the whole NSAttributedString with given font sizes.

And I would like to do this in separate NSOperation, so that user does not experience unnecessary UI lags.

Unfortunately, to count pages I need to draw my frames (CTFrameDraw) using invisible text drawing mode and then use CTFrameGetVisibleStringRange to count characters. But to draw a text I need a CGContext. And here the problems begin...

I can obtain a CGContext in my drawRect by calling UIGraphicsGetCurrentContext, but in this case:

  1. I have to call any method that operates on the CGContext using performSelectorOnM开发者_Python百科ainThread, right?
  2. The other thread should CFRetain this context. Is it acceptable to use drawRect's CGContext outside drawRect method?

Any other solutions? Creating separate CGContext in the worker thread? How? CGBitmapContext? How can I be sure that all conditions (i don't know, resolution? etc.) will be the same as in drawRect's CGContext, so that pages will be counted correctly?


You don't need to CTFrameDraw before getting result from CTFrameGetVisibleStringRange


You can use CTFramesetterSuggestFrameSizeWithConstraints.

See my question here: How to split long NSString into pages


use CTFramesetterSuggestFrameSizeWithConstraints ,if you specify the parameter of fitRange,it return the actual range of the string

+ (NSArray*) pagesWithString:(NSString*)string size:(CGSize)size font:(UIFont*)font;
{
  NSMutableArray* result = [[NSMutableArray alloc] initWithCapacity:32];
  CTFontRef fnt = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize,NULL);
  CFAttributedStringRef str = CFAttributedStringCreate(kCFAllocatorDefault, 
                                                       (CFStringRef)string, 
                                                       (CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:(id)fnt,kCTFontAttributeName,nil]);
  CTFramesetterRef fs = CTFramesetterCreateWithAttributedString(str);
  CFRange r = {0,0};
  CFRange res = {0,0};
  NSInteger str_len = [string length];
  do {
    CTFramesetterSuggestFrameSizeWithConstraints(fs,r, NULL, size, &res);
    r.location += res.length;
    [result addObject:[NSNumber numberWithInt:res.length]];
  } while(r.location < str_len);

  CFRelease(fs);
  CFRelease(str);
  CFRelease(fnt);
  return result;
}  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜