CocoaObjective-Cでテキストを画像に変換する方法の変更されたコードを使用して既存のテキストの上にテキストをレンダリングすることができましたNSImage
// Use Helvetica size 200
CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica Bold"), 200.0, nil);
// Setup the string attributes, set TEXT COLOR to WHITE
NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(__bridge id)(font), kCTFontAttributeName,
[[NSColor whiteColor] CGColor], (__bridge id)(kCTForegroundColorAttributeName),
nil];
NSAttributedString* as = [[NSAttributedString alloc] initWithString:string attributes:attributes];
CFRelease(font);
// Calculate the size required to contain the Text
CTLineRef textLine = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)as);
CGFloat ascent, descent, leading;
double fWidth = CTLineGetTypographicBounds(textLine, &ascent, &descent, &leading);
size_t w = (size_t)ceilf(fWidth);
size_t h = (size_t)ceilf(ascent + descent);
//Allocated data for the image
void* data = malloc(w*h*4);
// Create the context and fill it with white background
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
CGContextRef ctx = CGBitmapContextCreate(data, w, h, 8, w*4, space, bitmapInfo);
CGColorSpaceRelease(space);
CGContextSetRGBFillColor(ctx, 0.0, 0.0, 0.0, 0.0); // black background
CGContextFillRect(ctx, CGRectMake(0.0, 0.0, w, h));
// Draw the text in the new CoreGraphics Context
CGContextSetTextPosition(ctx, 0.0, descent);
CTLineDraw(textLine, ctx);
CFRelease(textLine);
// Save the CoreGraphics Context to a NSImage
CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc] initWithCGImage:imageRef];
NSImage *stringImage = [[NSImage alloc] initWithSize:size];
[stringImage addRepresentation:imageRep];
// Combine the original image with the new Text Image
[originalImage lockFocus];
[stringImage drawInRect:NSMakeRect(renderArea.origin.x, renderArea.origin.y, w, h) fromRect:NSZeroRect operation:NSCompositeSourceAtop fraction:1];
[originalImage unlockFocus];
CGImageRelease(imageRef);
free(data);