如何用关卡游戏场景的屏幕快照替换关卡按钮图像? [英] How can I replace level button image with a screenshot of the level game scene?
问题描述
我知道如何拍摄屏幕快照并将其保存到照片库.我使用下面的代码来做到这一点.我想用我的gameScene屏幕快照替换我的关卡场景按钮图像.假设我的图片按钮是150x150.我该如何实现?
I know how to take and save a screenshot to the photo library. I do this using the code below. I would like to replace my level scene button images with screenshots of my gameScene. Say my image buttons are 150x150. How can I achieve this?
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)
}
推荐答案
当UIGraphicsGetImageFromCurrentImageContext
返回UIImage
时,SKTexture
的启动器需要UIImage
和SKSpriteNode
(我假设您是正在为您的按钮使用)有一个带有SKTexture
和CGSize
的初始化程序,我认为您拥有所需的一切:
As UIGraphicsGetImageFromCurrentImageContext
returns a UIImage
, and SKTexture
has an initiaser that takes a UIImage
, and SKSpriteNode
(which I assume you are using for your button) has an initialiser that takes an SKTexture
and a CGSize
, I think you have everything you need:
if let screenshot = UIGraphicsGetImageFromCurrentImageContext() {
let screenShotTexture = SKTexture(image: screenshot)
let button = SKSpriteNode(texture: screenShotTexture, size: CGSize(width: 150, height: 150))
}
使用此方法,您无需将屏幕截图保存到相册中(除非您出于其他原因想要这么做).
Using this, you wouldn't need to save the screenshot to the photo album (unless you wanted to for other reasons).
这篇关于如何用关卡游戏场景的屏幕快照替换关卡按钮图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!