寻找使用 Cocoa 将文本写入 NSImage 的简单示例

Looking for simple example to write text into a NSImage using Cocoa

    NSImage *myNewIconImage=[[NSImage imageNamed:@"FanImage"] copy];
    [myNewIconImage lockFocus];
    [@"15" drawAtPoint:NSZeroPoint withAttributes:nil];
    [myNewIconImage unlockFocus];

    [myNewIconImage setTemplate:YES];
    [[NSApplication sharedApplication]] setApplicationIconImage:myNewIconImage];
    

我正在寻找一种方法来将字符串简单地写到这张图片上....而且非常简短。这对我不起作用。

以下代码将在 NSImage 上放置一个可变属性字符串:

NSImageView *imageView = [[NSImageView alloc] initWithFrame:NSMakeRect( 0, 0, _wndW, _wndH )]; 
[[window contentView] addSubview:imageView];
NSImage *image = [NSImage imageNamed:@"myImage.jpg"];
[image lockFocus];
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
[attr setObject:[NSFont fontWithName:@"Lucida Grande" size:36] forKey:NSFontAttributeName];
[attr setObject: [NSNumber numberWithFloat: 10.0] forKey: NSStrokeWidthAttributeName];
[attr setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
NSString *myStr = @"Welcome to Cocoa";
NSMutableAttributedString *s = [[NSMutableAttributedString alloc] initWithString: myStr attributes:attr];
[s drawAtPoint:NSMakePoint(130,130)];
[image unlockFocus];
[imageView setImage:image];