我有以下代码,它可以在“分享”按钮被点击时截图游戏屏幕并分享。
在模拟器上它运行得很好,并返回正确的图片。 但是,在我的真实设备上,它每次都返回白色的图片。
这是代码:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let Touch : UITouch! = touches.first
let TouchLocation = Touch.location(in: self)
if let body = self.physicsWorld.body(at: TouchLocation){
if body.node!.name == "shareButton" {
let postText: String = "Check out my score! Can you beat it?"
let postImage: UIImage = getScreenshot()
let activityItems = [postText as AnyObject, postImage] //as [Any]
let activityController = UIActivityViewController(
activityItems: activityItems,
applicationActivities: nil
)
let controller: UIViewController = scene!.view!.window!.rootViewController!
controller.present(
activityController,
animated: true,
completion: nil
)
}
}
}
这里是函数的实现:
func getScreenshot() -> UIImage {
let snapshotView = self.view!.snapshotView(afterScreenUpdates: true)
let bounds = UIScreen.main.bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
snapshotView?.drawHierarchy(in: bounds, afterScreenUpdates: true)
let screenshotImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return screenshotImage;
}
我将问题缩小到了这几行代码:
let postText: String = "Check out my score! Can you beat it?"
let postImage: UIImage = getScreenshot()
let activityItems = [postText as AnyObject, postImage] //as [Any]
let activityController = UIActivityViewController(
activityItems: activityItems,
applicationActivities: nil
)
let controller: UIViewController = scene!.view!.window!.rootViewController!
controller.present(
activityController,
animated: true,
completion: nil
)
func getScreenshot() -> UIImage {
let snapshotView = self.view!.snapshotView(afterScreenUpdates: true)
let bounds = UIScreen.main.bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
snapshotView?.drawHierarchy(in: bounds, afterScreenUpdates: true)
let screenshotImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return screenshotImage;
}
请注意,我只使用一个类。这个类是:
。
class GameScene: SKScene {
}
我通过创建一个新应用程序来缩小了范围。除了添加这些代码行外,我没有对默认的Hello World应用程序进行任何更改。它们返回相同的结果:空白图像。
非常感谢您的帮助!