有什么方法可以从 NSTextField 创建 NSImage 吗?我正在制作一个应该捕获用户文本并生成 PNG 文件的应用程序。
问问题
1160 次
2 回答
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
如果您只想要字符串,请使用 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;
}
于 2012-12-28T10:56:26.557 回答
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
}
于 2019-05-14T10:08:13.303 回答