2017-04-06 51 views
7

我知道如何拍攝並保存照片庫的截圖。我使用下面的代碼來執行此操作。我想用我的gameScene的屏幕截圖替換我的關卡場景按鈕圖像。假設我的圖片按鈕是150x150。我怎樣才能做到這一點?如何用水平遊戲場景的屏幕截圖替換水平按鈕圖像?

func takeScreenShot(scene:SKScene) { 
    let bounds = self.scene!.view?.bounds 
    UIGraphicsBeginImageContextWithOptions(/*CGRect(x: 0, y: 0, width: 100, height: 100).size*/bounds!.size, true, UIScreen.main.scale) 
    self.scene?.view?.drawHierarchy(in: bounds!, afterScreenUpdates: true) 
    let screenshot = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 
    UIImageWriteToSavedPhotosAlbum(screenshot!, nil, nil, nil) 

} 


class LevelSelectScene: SKScene { 

let button1: SKSpriteNode = SKSpriteNode(imageNamed: "image1") 
let button2: SKSpriteNode = SKSpriteNode(imageNamed: "image2") 
let button3: SKSpriteNode = SKSpriteNode(imageNamed: "image3") 

        ... 

override init(size: CGSize){ 
super.init(size: size) 

button1.position = CGPoint(x: self.frame.width/4, y: self.frame.height/2) 
self.addChild(button1) 

button2.position = CGPoint(x: self.frame.width/2, y: self.frame.height/2) 
self.addChild(button2) 

button3.position = CGPoint(x: 3*self.frame.width/4, y: self.frame.height/2) 
self.addChild(button3) 

} 

回答

3

由於UIGraphicsGetImageFromCurrentImageContext返回UIImageSKTexture有initiaser,需要一個UIImageSKSpriteNode(我假設你正在使用您的按鈕)有一個初始化器接受一個SKTextureCGSize,我想你有你需要的一切:

if let screenshot = UIGraphicsGetImageFromCurrentImageContext() { 
    let screenShotTexture = SKTexture(image: screenshot) 
    let button = SKSpriteNode(texture: screenShotTexture, size: CGSize(width: 150, height: 150)) 
} 

利用這一點,你就不會需要將屏幕截圖保存到相冊(除非你想爲其他原因)。

+0

當然,如果你想建立一個按鈕的集合,那麼只需將各種紋理保存到一個數組。 –

+0

'截圖'是一個可選項 – 0x141E