有没有办法从NSTextField创建NSImage?我正在创建一个应该捕获用户文本并生成PNG文件的应用程序。
答案 0 :(得分:2)
是的,让视图绘制成图像:
-(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;
}
答案 1 :(得分:0)
在Swift 5中:
private func convertTextFieldToImage() -> NSImage? {
let myRect = timerLabel.bounds
let mySize = myRect.size
guard let bitmapImageRepresentation = timerLabel.bitmapImageRepForCachingDisplay(in: myRect) else {
return nil
}
bitmapImageRepresentation.size = mySize
timerLabel.cacheDisplay(in: myRect, to: bitmapImageRepresentation)
let image = NSImage(size: mySize)
image.addRepresentation(bitmapImageRepresentation)
return image
}