Skip to content

Instantly share code, notes, and snippets.

@aki-null
Created December 19, 2011 15:23
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aki-null/1497649 to your computer and use it in GitHub Desktop.
Save aki-null/1497649 to your computer and use it in GitHub Desktop.
Core Text APIを使用した際に起こる行間の問題の回避
NSFont *normalFont = [NSFont systemFontOfSize:12];
CGRect renderFrame = CGRectMake(0, 0, 300, 50); // box to render the text into
static NSLayoutManager *layMan = nil;
if (!layMan) {
layMan = [NSLayoutManager new];
}
CGFloat lineHeight = [layMan defaultLineHeightForFont:normalFont]; // calculate the expected height of a line
NSDictionary *attrDict = [NSDictionary dictionaryWithObject:normalFont andKey:NSFontAttributeName];
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"テスト\nテスト\ntest\nテスト" attributes:attrDict];
CTFramesetterRef frameSttr = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrStr);
[attrStr release];
renderFrame = 1000000;
CGPathRef framePath = CGPathCreateMutable();
CGPathAddRect((CGMutablePathRef)framePath, NULL, renderFrame);
CTFrameRef ctFrm = CTFramesetterCreateFrame(frameSttr, CFRangeMake(0, 0), framePath, NULL);
CFRelease(frameSttr);
CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
CGContextSaveGState(context);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextScaleCTM(context, 1.0, -1.0); //flip only when this view is flipped
NSArray *lines = (NSArray *)CTFrameGetLines(ctFrm);
CFIndex linesCount = [lines count];
for (NSUInteger i = 0; i < linesCount; i++) {
// the Y coordinate calculation assumes that the view coordinate system is flipped
CGContextSetTextPosition(context, renderFrame.origin.x, renderFrame.origin.y + renderFrame.size.height - (lineHeight + 1) * (i + 1));
CTLineDraw((CTLineRef)[lines objectAtIndex:i], context);
}
CFRelease(ctFrm);
CGContextRestoreGState(context);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment