How to take screen shot programmatically (Swift, SpriteKit)
Asked Answered
P

2

11

I tried what ever was suggested but the output was a white,blank screenshot. Which leads me to assume that I haven't added anything to the view. Here's how I'm adding graphics to my view. The addChild method comes with the SpriteKit and it takes in SKSpriteNodes:

  addChild(background)
    addChild(rate)
    addChild(scoreLabel)
    addChild(share)
    addChild(playAgain)
    addChild(highScoreLabel)
    addChild(scoreBackground)
    addChild(highScoreBackground)

Here's the method that takes the screenshot:

    UIGraphicsBeginImageContext(self.view!.bounds.size)
    self.view!.layer.renderInContext(UIGraphicsGetCurrentContext())
    let screenshot = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)

Any suggestions would be helpful

Phycomycete answered 30/12, 2014 at 18:59 Comment(3)
the addChild method comes with the SpriteKit framework. I'm not sure what it's adding them to. But I use it to make the sprites visible. However when I use the screenshot method it returns a white , blank screenshot.Phycomycete
You have to call addChild on some SKNode. With the code you've posted it's not clear what view or node you're adding them to (if any)Iglesias
Marking me down for what? I lost two points for what? This is ridiculous and you guys should be ashamed.Phycomycete
R
12

I think this question could be merged with this one Screenshotting on Iphone in swift only has a white background

which seems the same

EDIT:

I think I found a solution. First read this post: How Do I Take a Screen Shot of a UIView?

I create an Extensions.swift file in which I 'extended' the methods of a UIView using that link.

After that I simply connect the following to my sprite-kit button

let screenshot = self.view?.pb_takeSnapshot()
UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)

Voilà, the image is in the camera roll!

Rota answered 4/1, 2015 at 10:29 Comment(1)
Thank you! I appreciate your answer.Phycomycete
S
4

Here is how I solved it in swift 3: This captures all the nodes in your scene: Note: in below code represents the view it is capturing from. You may want to update it with your view in project.

func captureScreen() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(yourview.bounds.size, true, 0)

    yourview.drawHierarchy(in: yourview.bounds, afterScreenUpdates: true)


    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}
Salvatore answered 18/9, 2016 at 5:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.