2015-08-30 34 views

回答

0

不是在Swift中,但它應該給你一個關於如何去做的好主意。

你可以這樣做捕獲屏幕到一個UIImage:

CGRect bounds = self.scene.view.bounds; 
UIGraphicsBeginImageContextWithOptions(bounds.size, NO, [UIScreen mainScreen].scale); 
[self drawViewHierarchyInRect:bounds afterScreenUpdates:YES]; 
UIImage* screenshotImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

然後創建一個從UIImage的PNG圖像(並將其寫入到磁盤)是這樣的:

// Create paths to output images 
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"]; 
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"]; 

來源here

// Write a UIImage to JPEG with minimum compression (best quality) 
// The value 'image' must be a UIImage object 
// The value '1.0' represents image compression quality as value from 0.0 to 1.0 
[UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES]; 

// Write image to PNG 
[UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES]; 

// Let's check to see if files were successfully written... 

// Create file manager 
NSError *error; 
NSFileManager *fileMgr = [NSFileManager defaultManager]; 

// Point to Document directory 
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 

// Write out the contents of home directory to console 
NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]); 

來源here

0

下面是如何將視圖內容寫入PNG文件的示例。首先,定義一個UIView擴展,捕獲視圖的內容並將其轉換爲UIImage

extension UIView { 
    func screenGrab() -> UIImage { 
     // Uncomment this (and comment out the next statement) for retina screen capture 
     // UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale) 
     UIGraphicsBeginImageContextWithOptions(bounds.size, false, 1.0) 
     drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true) 
     let image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return image 
    } 
} 

然後,定義一個將UIImage寫入文件的UIImage擴展。

extension UIImage { 
    func writeToFile(fileName:String) { 
     let path = NSHomeDirectory().stringByAppendingPathComponent("Documents/"+fileName) 
     UIImagePNGRepresentation(self).writeToFile(path, atomically: true) 
    } 
} 

最後,採集和

self.view?.screenGrab().writeToFile("capture.png") 

寫視圖爲PNG文件的內容,這裏是如何確定的PNG圖像將被存儲:

println(NSHomeDirectory().stringByAppendingPathComponent("Documents")) 
+0

我把它這將適用於iOS,因爲它使用UIKit,但我希望它適用於Mac應用程序。有使用AppKit的等價物嗎? – wes

+0

對不起。我錯過了osx標籤。我必須研究這一點。 – Epsilon