2013-12-17 170 views
7

只是玩弄SpriteKit,並試圖弄清楚如何捕捉一個SKNode到'UIImage'的'抓取'。如何渲染一個SKNode到UIImage

使用UIView(或UIView子類),我已經使用視圖的layer屬性渲染到圖形上下文中。

例如,

#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(); 

回答

9

這將捕獲整個場景。您還可以使用轉換爲UIKit座標的累加幀來僅捕獲有問題的節點及其子節點的區域。

或者,您可以從該節點層級的特定部分得到SKTexture

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

此前的iOS 9,有沒有辦法的SKTexture轉換回UIImage。然而,現在,它是微不足道的:

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

謝謝。結果將再次用於Sprite Kit - so textureFromNode:非常出色。乾杯! –

+0

@ learncocos2d這是否仍然是最好的方法? –

+0

@StevenRitchie不幸的是。 – ColdSteel