如何从SKTexture
获取UIImage
我试图从SKTextureAtlas
获取UIImage
,但似乎也不起作用:
// p40_prop1 is a part of SKTextureAtlas
UIImage *image = [UIImage imageNamed:@"p40_prop1"];
image
为零。
发布于 2015-10-09 15:35:46
从iOS 9开始,这是小菜一碟。SKTexture
现在具有CGImage
属性,该属性属于CGImageRef
类型。所以从纹理中获取图像现在只有一行代码:
let image : UIImage = UIImage(CGImage:texture.CGImage)
发布于 2014-02-06 11:00:16
在iOS 7.0中,实际上有一种方法可以从SKView中提取UIImage!
它使用常规的UIView API将视图呈现为一个ImageContext,然后从中提取一个UIImage。但是,此解决方案的范围非常有限。它将SKView绘制到UIImage中,然后裁剪得到的图像以适合给定节点的帧。因此,不能有任何内容覆盖您要创建快照节点。此外,视图和场景都必须在屏幕上可见(这比通常的-[SKView textureFromNode:]
方法更严格)。甚至可能还有我还没有发现的更多限制。
考虑到所有这些,这个过程仍然足够满足我的需要,所以我认为它值得分享。
+(UIImage *)imageFromNode:(SKNode *)node {
SKView *view = node.scene.view;
CGFloat scale = [UIScreen mainScreen].scale;
CGRect nodeFrame = [node calculateAccumulatedFrame];
// render SKView into UIImage
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
UIImage *sceneSnapshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// crop to the requested node (making sure to flip the y-coordinate)
CGFloat originY = sceneSnapshot.size.height*scale - nodeFrame.origin.y*scale - nodeFrame.size.height*scale;
CGRect cropRect = CGRectMake(nodeFrame.origin.x * scale, originY, nodeFrame.size.width*scale, nodeFrame.size.height*scale);
CGImageRef croppedSnapshot = CGImageCreateWithImageInRect(sceneSnapshot.CGImage, cropRect);
UIImage *nodeSnapshot = [UIImage imageWithCGImage:croppedSnapshot];
CGImageRelease(croppedSnapshot);
return nodeSnapshot;
}
我已经在3.5英寸和4英寸视网膜iPhones,视网膜和非视网膜iPads的模拟器上测试了这一点。至于实际的设备,它可以在iPhone 4S,iPhone 5S和iPad 2上运行,都运行7.0.4。
发布于 2014-01-11 20:22:39
从iOS 7.0开始,无法从SKTexture、SKTextureAtlas或SKView获取UIImage。
https://stackoverflow.com/questions/21061248
复制相似问题