gpt4 book ai didi

cocoa - 将 NSTextField 转换为 NSImage?

转载 作者:行者123 更新时间:2023-12-03 17:41:12 27 4
gpt4 key购买 nike

有什么方法可以从 NSTextField 创建 NSImage 吗?我正在制作一个应用程序,它应该捕获用户文本并生成 PNG 文件。

最佳答案

是的,让 View 绘制成图像:

-(NSImage *)imageOfView:(NSView*)view
{
NSRect myRect = view.bounds;
NSSize imgSize = myRect.size;

NSBitmapImageRep *bir = [view bitmapImageRepForCachingDisplayInRect:myRect];
[bir setSize:mySize];
[view cacheDisplayInRect:myRect toBitmapImageRep:bir];

NSImage* image = [[[NSImage alloc]initWithSize:mySize] autorelease];
[image addRepresentation:bir];
return image;
}

来自 http://www.stairways.com/blog/2009-04-21-nsimage-from-nsview

<小时/>

如果您只想要 STRING,请使用 NSString 的 drawString 方法自行渲染它,如下所示:

-(NSImage *)imageWithText(NSString*)string:
{
NSSize mySize = NSMakeSize(50,100); //or measure the string

NSBitmapImageRep *bir = NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:(unsigned char **)&bitmapArray
pixelsWide:mySize.width pixelsHigh:mySize.height
bitsPerSample:8
samplesPerPixel:3 // or 4 with alpha
hasAlpha:NO
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:0
bytesPerRow:0 // 0 == determine automatically
bitsPerPixel:0]; // 0 == determine automatically

//draw text using -(void)drawInRect:(NSRect)aRect withAttributes:(NSDictionary *)attributes

NSImage* image = [[[NSImage alloc]initWithSize:mySize] autorelease];
[image addRepresentation:bir];
return image;
}

关于cocoa - 将 NSTextField 转换为 NSImage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14068306/

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