2015-04-25 83 views
4

嗨我正在做一個遊戲,我已經添加了一個共享按鈕的遊戲。我希望用戶能夠在一條消息中彼此共享消息,URL和屏幕截圖。它的共享方面工作正常,除了屏幕截圖本身顯示空白以外,一切都顯示出來了。這是我使用採取截圖的代碼:截圖顯示空白 - 斯威夫特

let layer = UIApplication.sharedApplication().keyWindow!.layer 
    let scale = UIScreen.mainScreen().scale 
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale); 

    layer.renderInContext(UIGraphicsGetCurrentContext()) 
    let screenshot = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 

    UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil) 

    println("screenshot") 

請幫我解決這個問題,請務必在斯威夫特的語言這樣做。此外,我使用SpriteKit技術,如果這有所作爲。我對編碼很陌生,所以請非常清楚。非常感謝你!

回答

9

更新:的Xcode 8.2.1•斯威夫特3.0.2

您需要添加import語句,這擴展到您的遊戲場景:

import UIKit 

extension UIView { 
    var snapshot: UIImage? { 
     UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0) 
     defer { UIGraphicsEndImageContext() } 
     drawHierarchy(in: bounds, afterScreenUpdates: true) 
     return UIGraphicsGetImageFromCurrentImageContext() 
    } 
} 

let myImage = view?.snapshot 
+0

可以請你看看我的問題http://stackoverflow.com/questions/43246482/how-can-i-replace-level-button-image-with-a-screenshot-of-the-level-遊戲場景。我真的很感激任何幫助 – Hilarious404

5

在WWDC 2中015,UIVisualEffectView中有什麼新功能,解決方案是「掩蓋」,捕捉包含活力標籤和模糊的UIVisualEffectView截圖。經常出現的問題是Apple的屏幕截圖API往往無法捕捉到UIVisualEffect,導致視圖的屏幕截圖沒有視覺效果。根據WWDC 2015的解決方案涉及在窗口/屏幕捕獲快照;不幸的是,示例代碼沒有顯示。以下是我自己的實現:

//create snapshot of the blurView 
let window = UIApplication.sharedApplication().delegate!.window!! 
//capture the entire window into an image 
UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, UIScreen.mainScreen().scale) 
window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: true) 
let windowImage = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 
//now position the image x/y away from the top-left corner to get the portion we want 
UIGraphicsBeginImageContext(blurView.frame.size) 
windowImage.drawAtPoint(CGPoint(x: -blurView.frame.origin.x, y: -blurView.frame.origin.y)) 
let croppedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext(); 
//embed image in an imageView, supports transforms. 
let resultImageView = UIImageView(image: croppedImage) 

注意:此快照代碼只有在ViewDidAppear被調用後纔有效。