如何渲染一个SKNode到UIImage

只是玩弄SpriteKit,并试图找出如何捕捉到一个SKNode'抢'成UIImage。

使用UIView(或UIView子类),我已经使用视图的layer属性来渲染成graphics上下文。

例如。

 #import <QuartzCore/QuartzCore.h> + (UIImage *)imageOfView:(UIView *)view { UIGraphicsBeginImageContextWithOptions(view.frame.size, YES, 0.0f); CGContextRef context = UIGraphicsGetCurrentContext(); [view.layer renderInContext:context]; UIImage *viewShot = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return viewShot; } 

SKNode不是UIView的子类,因此看起来并不支持图层。

任何想法,我可能会去渲染一个给定的SKNode到UIImage?

这将捕捉整个场景:

 CGRect bounds = self.scene.view.bounds; UIGraphicsBeginImageContextWithOptions(bounds.size, NO, [UIScreen mainScreen].scale); [self drawViewHierarchyInRect:bounds afterScreenUpdates:YES]; UIImage* screenshotImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

如果你只想要一个特定的节点分支,你可以在截图之前隐藏你不想捕获的所有节点。 您还可以使用转换为UIKit坐标的累积帧来仅​​捕获节点及其子节点的区域。

或者,您可以从节点层次结构的特定部分获取SKTexture

 SKTexture* tex = [self.scene.view textureFromNode:yourNode]; 

在iOS 9之前,没有办法将SKTexture转换回UIImage 。 然而现在,这是微不足道的:

 UIImage *image = [UIImage imageWithCGImage:tex.CGImage];