gpt4 book ai didi

objective-c - NSString drawAtPoint 文本未显示

转载 作者:行者123 更新时间:2023-12-03 16:37:54 24 4
gpt4 key购买 nike

在我的应用程序中,我以编程方式构建一个 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];
}

最佳答案

使用 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);

关于objective-c - NSString drawAtPoint 文本未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13187881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com