如何以编程方式在Spritekit中截取屏幕截图?

时间:2014-05-21 18:17:11

标签: ios uiimage screenshot sprite-kit

我一直在阅读有关如何以编程方式截取屏幕截图的已解决的问题,但我似乎无法获得我在sprite工具包中阅读的内容。例如:

这个问题How to take a screenshot programmatically

   UIGraphicsBeginImageContext(self.window.bounds.size);
    [self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData * data = UIImagePNGRepresentation(image);
    [data writeToFile:@"foo.png" atomically:YES];

更新2011年4月:对于视网膜显示,将第一行更改为:

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
else
    UIGraphicsBeginImageContext(self.window.bounds.size);

给了我这些信息,我在游戏中测试了这些信息,但它没有工作,因为SKScene上没有识别窗口。我尝试用场景替换它但是没有用。有什么建议?

我也试过这个:

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, scale);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

我在这个问题中找到了:ios Sprite Kit screengrab?

但它似乎无法发挥作用,因为它无法识别第二行中的比例或界限。

4 个答案:

答案 0 :(得分:6)

这是在Spritekit中截取屏幕截图的最佳解决方案

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 1);
[self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return  viewImage;

答案 1 :(得分:3)

func screenShot() {

    UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, 0)
    self.view!.drawViewHierarchyInRect(self.view!.bounds, afterScreenUpdates: true)
    var image:UIImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    var Image = image //The image is stored in the variable Image

}

screenshot() //Calls the function and takes a screenshot

答案 2 :(得分:1)

// Full Screen Shot function. Hope this will work well in spritekit.   
func screenShot() -> UIImage {                                                    
 UIGraphicsBeginImageContext(CGSizeMake(frame.size.width, frame.size.height))
 var context:CGContextRef  = UIGraphicsGetCurrentContext()
 self.view?.drawViewHierarchyInRect(frame, afterScreenUpdates: true)
 var screenShot = UIGraphicsGetImageFromCurrentImageContext()
 UIGraphicsEndImageContext();  
 return screenShot 
}

答案 3 :(得分:-2)

您可以为任意视图拍摄屏幕截图。UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *gameOverScreenImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();