如何将SKNode渲染为UIImage [英] How to render a SKNode to UIImage

查看:129
本文介绍了如何将SKNode渲染为UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是玩SpriteKit并试图弄清楚如何将SKNode的'抓取'捕获到UIImage中。

Just playing around with SpriteKit and am trying to figure out how to capture a 'grab' of an SKNode into a UIImage.

使用UIView(或UIView子类) ),我已经使用视图的图层属性渲染到图形上下文中。

With UIView (or a UIView subclass), I have used the layer property of the view to render into a graphics context.

例如。

#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 is not a subclass of UIView and thus does not appear to be backed by a layer.

关于如何将给定的SKNode渲染为UIImage的任何想法?

Any ideas of how I might go about rendering a given SKNode to a UIImage?

推荐答案

这将捕获整个场景:

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

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

If you want just a particular node branch you can hide all nodes you don't want to capture before taking the screenshot. You can also use accumulated frame converted to UIKit coordinates to capture only the area of the node and its children in question.

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

Alternately, you can get an SKTexture from a specific part of the node hierarchy:

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

在iOS 9之前,无法转换 SKTexture 返回 UIImage 。然而,现在,它是微不足道的:

Prior to iOS 9, there wasn't way to convert an SKTexture back to a UIImage. Now, however, it's trivial:

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

这篇关于如何将SKNode渲染为UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆