【问题标题】:Add Customized UIView to Scenekit's node将自定义 UIView 添加到 Scenekit 节点
【发布时间】:2019-10-24 14:13:54
【问题描述】:

我是 Scenekit 开发的初学者,我正在尝试将 UIView 添加为 SCNPlane 节点的漫反射内容,但遇到了一些奇怪的崩溃。

代码:

   override func viewDidLoad() {
        super.viewDidLoad()
        let scene = SCNScene()
        let plane = SCNPlane(width: 0.1, height: 0.1)
        plane.firstMaterial?.diffuse.contents = getCustomView()
        let planeNode = SCNNode(geometry: plane)
        planeNode.position = SCNVector3(0, 0, 0)
        scene.rootNode.addChildNode(planeNode)
        sceneView.scene = scene
    }

    func getCustomView() -> UIView {
        let view = UIView()
        view.backgroundColor = .red
        return view
    }

崩溃:

我正在尝试通过设计 UIView 来实现以下输出

请告诉我如何将 UIView 添加为 SCNNode 的漫反射内容。

【问题讨论】:

  • 各位,好运吗?

标签: ios swift sprite-kit uikit scenekit


【解决方案1】:

您在这里混合乐高积木和 K'Nex。

让我们去文档看看什么是 SCNMaterial 的有效漫反射内容:

您可以使用以下任一方法为此属性设置值 类型:

一种颜色(NSColor/UIColor 或 CGColor),为 材料表面

一个数字(NSNumber),指定一个统一的标量值 材料的表面(适用于基于物理的属性,例如 金属度)

一个图像(NSImage/UIImage 或 CGImage),指定一个纹理为 映射到材料的表面

一个指定图像文件位置的 NSString 或 NSURL 对象

视频播放器 (AVPlayer) 或实时视频捕获预览 (AVCaptureDevice,仅限 iOS)

一个核心动画层(CALayer)

纹理(SKTexture、MDLTexture、MTLTexture 或 GLKTextureInfo)

SpriteKit 场景 (SKScene)

一个特殊格式的图像或六个图像的数组,指定 立方体贴图的面

当您检查从文件加载的场景元素时,此值为 总是一个颜色对象(NSColor 或 UIColor 类, 根据平台)或图像对象(NSImage 或 UIImage 类,根据平台)。因此,您可以使用类型 自省(Objective-C 中的 isKind(of:) 方法,或者 is 运算符或 Swift 中的 let-as 匹配)来确定 物质属性的内容。 https://developer.apple.com/documentation/scenekit/scnmaterialproperty/1395372-contents

让我们看看 UIView 是什么:

类 UIView : UIResponder
类 UIResponder : NSObject
https://developer.apple.com/documentation/uikit/uiview
https://developer.apple.com/documentation/uikit/uiresponder

如您所见,UIView 不是有效类型。

但是,UIView 确实包含 CALayer

https://developer.apple.com/documentation/uikit/uiview/1622436-layer

所以你应该能够使用它从你的视图中获得你需要的东西:

func getCustomViewLayer() -> CALayer {
    let view = UIView()
    view.backgroundColor = .red
    return view.layer
}

【讨论】:

  • 谢谢@knightOfDragon 我会检查并回复你
  • @knightOfDragon 它给了我同样的崩溃
  • 看起来其他东西正在崩溃,当您的内容为零时它会崩溃吗?
  • 将场景设置为sceneView的场景时崩溃了
  • 我对场景套件不熟悉,但有些东西指向 nil,看起来不应该是 nil
【解决方案2】:

使用此扩展从 UIView 获取图像表示

public extension UIView {
 @available(iOS 10.0, *)
 var image: UIImage {
    let renderer = UIGraphicsImageRenderer(bounds: bounds)
    return renderer.image { rendererContext in
        layer.render(in: rendererContext.cgContext)
    }
  }
}

并在您的自定义视图上调用它,如下所示:

getCustomView().image

最后在您的 SCNNode 平面上,如下所示:

plane.firstMaterial?.diffuse.contents = getCustomView().image

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 2012-09-01
    • 2018-01-20
    • 2018-05-05
    • 1970-01-01
    相关资源
    最近更新 更多