2

在我的应用程序中,我正在以编程方式构建一个NSImage对象,该对象设置为应用程序停靠图标。我想在图标上添加一些文本,并且一直在尝试使用NSString drawAtPoint: withAttributes,但它似乎不起作用。我已经使用日志消息确认字符串构造正确。

我似乎无法弄清楚我错过了什么,做错了什么。任何帮助将不胜感激。

这是我为绘制到NSImage

-(void) drawStringToImage:(NSString*) str{

    [theIcon lockFocus];

    NSLog([@"Drawing String: " stringByAppendingString:str]);
   //  [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
    [str drawAtPoint:NSMakePoint(5,500) withAttributes:nil];

    [theIcon unlockFocus];
}
4

1 回答 1

2

使用How to convert Text to Image in Cocoa Objective-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);
于 2012-11-02T14:55:02.563 回答