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