swift - 如何正确使用 NSImage 作为 SCNGeometry 形状的 Material ?

标签 swift xcode macos

我在大学里接到了一个任务,要为 SCNGeometry Octahedron 添加一张图片作为纹理。这是我在 Swift 中的第一个项目。

对于带有 UIImage 类的 UIKit 有很多建议,但我使用的是 AppKit for macos 和 NSImage 类。我在网上找到的所有选项都还没有对我有用。可能我误解了一些基本的东西。 好吧,首先我将一张名为“sims.jpg”的图片拖放到我的项目文件夹和 art.scnassets 文件夹中。并且还通过文件 → 添加文件到“art.scnassets”和通用文件夹来添加它们。并且不对 Assets.xcassets 做任何事情。

然后这里是如何创建形状的:

func createOctahedron() {

   let vertices: [SCNVector3] = [
       SCNVector3(0, 1, 0),
       SCNVector3(-0.5, 0, 0.5),
       SCNVector3(0.5, 0, 0.5),
       SCNVector3(0.5, 0, -0.5),
       SCNVector3(-0.5, 0, -0.5),
       SCNVector3(0, -1, 0)
   ]

   let source = SCNGeometrySource(vertices: vertices)

   let indices: [UInt16] = [
       0, 1, 2,
       2, 3, 0,
       3, 4, 0,
       4, 1, 0,
       1, 5, 2,
       2, 5, 3,
       3, 5, 4,
       4, 5, 1
   ]

   let element = SCNGeometryElement(indices: indices, primitiveType: .triangles)
   let geometry = SCNGeometry(sources: [source], elements: [element])
   let node = SCNNode(geometry: geometry)

   node.geometry?.firstMaterial?.diffuse.contents = NSColor.green // назначаем цвет октаэдру

   let scnView = self.view as! SCNView
   scnView.scene?.rootNode.addChildNode(node)

   let rotateAction = SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: .pi, z: 0, duration: 5))
   node.runAction(rotateAction)
}

以防万一让我留下一个full code

所以,我会像这样添加图像

let imageMaterial = SCNMaterial()
let image = NSImage.Name("sims")
imageMaterial.diffuse.contents = image
geometry.materials = [imageMaterial, imageMaterial, imageMaterial, imageMaterial, imageMaterial, imageMaterial, imageMaterial, imageMaterial]

或者可能是那样?

node.geometry?.firstMaterial?.diffuse.contents = NSImage.Name("sims")

或者我应该以某种方式另外映射它吗?请帮助我,因为我真的不明白。 Xcode 只输出一个旋转的八面体,没有额外的纹理,也没有错误

最佳答案

这里是这一行:

let image = NSImage.Name("sims")

只声明名称。你需要:

let image = NSImage(named: NSImage.Name("sims"))

您的代码编译的原因是 contents 属性具有 Any? 类型,因此您可以将任何旧 goo 放入属性中。它默默地失败了。

关于swift - 如何正确使用 NSImage 作为 SCNGeometry 形状的 Material ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881717/

相关文章:

xcode - 阻止 Xcode 将文本转换为超链接?

swift - 如何在不将密码放入 Vapor 3 的 configure.swift 的情况下配置 Fluent/MySQL 数据库连接?

ios - 如何用一个全新的 Swift 项目覆盖 Objective-C 项目(重新开始)?

Mac 上 xcode 的 C++ bool 逻辑语法

ios - CABasicAnimation CGRect 扩大不工作

收听 unix 套接字时检查发件人

arrays - 从 SwiftUI 中的列表中删除绑定(bind)

swift - 如果调用 NSApp.terminate,DispatchQueue 线程会被清理吗?

macos - NSTableView 单元格的自定义选定图标

objective-c - 调整 NSTableView DraggingSession 的坐标