这是我用来在核心图形中显示一些文本的代码:
int y = MESSAGE_FRAME.origin.y + 8;
if (month) y = y + 27;
int height = [JHomeViewCellContentView heightOfMessage:self.entry.message];
CGRect rect = CGRectMake(MESSAGE_FRAME.origin.x + 8, y, MESSAGE_FRAME.size.width - 16, height);
UIFont *font = [UIFont fontWithName:@"Crimson" size:15.0f];
[[UIColor colorWithWhite:0.2 alpha:1.0] setFill];
[self.entry.message drawInRect:rect withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
如果我想在核心文本中显示相同的文本,这里是代码:
CGRect rect2 = CGRectMake(MESSAGE_FRAME.origin.x + 8, self.bounds.size.height - y - height + 2, MESSAGE_FRAME.size.width - 16, height);
UIFont *font = [UIFont fontWithName:@"Crimson" size:15.0f];
CGFloat lineHeight = [font lineHeight];
CTFontRef fontRef = CTFontCreateWithName((CFStringRef)@"Crimson", 15.0f, NULL);
CGFloat lineSpacing = 0;
CTParagraphStyleSetting settings[] = {
{ kCTParagraphStyleSpecifierMinimumLineHeight, sizeof(lineHeight), &lineHeight },
{ kCTParagraphStyleSpecifierMaximumLineSpacing, sizeof(lineSpacing), &lineSpacing },
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, sizeof(settings) / sizeof(settings[0]));
NSMutableDictionary *attDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
(__bridge_transfer id)fontRef, (NSString *)kCTFontAttributeName,
(id)[[UIColor colorWithWhite:0.2 alpha:1.0] CGColor], (NSString *)kCTForegroundColorAttributeName,
paragraphStyle, kCTParagraphStyleAttributeName,
nil];
NSAttributedString *attString = [[NSAttributedString alloc] initWithString:self.entry.message attributes:attDictionary];
//Flip the coordinate system
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, rect2);
self.framesetter = CTFramesetterCreateWithAttributedString((__bridge_retained CFAttributedStringRef)attString);
CTFrameRef theFrame = CTFramesetterCreateFrame(self.framesetter, CFRangeMake(0, [attString length]), path, NULL);
CFRelease(path);
CTFrameDraw(theFrame, context);
CFRelease(theFrame);
显然,尽管更加冗长,核心文本意味着比核心图形更快,这就是我学会如何做到这一点的原因。但是在仪器中运行这段代码,核心图形实现了 5 毫秒,而核心文本在 14 毫秒内完成。我觉得我在这里错过了一些东西。drawInRect 几乎快了 3 倍,我听说它应该更慢。我已经尽我所知改进了底部的代码,但我不是专家,我会很感激任何帮助。
为了澄清,我正在将一段文本绘制到视图上。这就是我想做的。并且所有文本都具有相同的外观。