2012-03-02 28 views
13

我试图将NSView的内容保存为图像,但只保存滚动视图内可见的图像。保存整个NSView内容,这是在NSScrollView内

下面是视图中加载的实际图像: actual image

但是,这是我是如何能够将图像保存: saved image

有什么办法来保存在一个NSView整个图像?

这是我如何救了我的NSView子类:

- (void)save 
{ 
    [self lockFocus]; 
    NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self bounds]]; 
    [self unlockFocus]; 

    NSData* data = [rep representationUsingType:NSPNGFileType properties:nil]; 

    NSString* string = NSHomeDirectory(); 
    NSString* pth1 = [string stringByAppendingPathComponent:@"ttx.png"]; 

    [data writeToFile:pth1 atomically:YES]; 
} 

这种方法是查看我要救。

+3

如何你现在在做什么? – hamstergene 2012-03-02 18:02:24

+0

@hamstergene我用我目前用来保存的代码编辑了我的问题。这是正确的方式吗? – Alterecho 2012-03-03 01:21:37

回答

17

使用-[NSView cacheDisplayInRect:toBitmapImageRep:]

NSBitmapImageRep* rep = [self bitmapImageRepForCachingDisplayInRect:self.bounds]; 
[self cacheDisplayInRect:self.bounds toBitmapImageRep:rep]; 
+0

它使用这两种方法!我以前不知道如何使用这些方法。谢谢! – Alterecho 2012-03-03 10:38:29

+0

终于有用的东西。 SO上有很多错误的,部分的或有问题的解决方案...... – mojuba 2013-10-29 17:51:24