NSString drawAtPoint文本未显示

时间:2012-11-02 01:10:57

标签: objective-c macos cocoa

在我的应用程序中,我是以编程方式构建一个NSImage对象,我将其设置为应用程序停靠Icon。我想在图标中添加一些文字并尝试使用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];
}

1 个答案:

答案 0 :(得分: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);