【发布时间】:2019-05-04 20:00:16
【问题描述】:
我在大学接到了一项任务,将图片作为纹理添加到 SCNGeometry 八面体。这是我在 Swift 中的第一个项目。
对于带有 UIImage 类的 UIKit 有很多建议,但我将 AppKit 用于 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 只输出一个旋转的八面体,没有额外的纹理,也没有错误
【问题讨论】:
-
你的图片不是 NSImage,它是 NSImage.Name。您可以使用该名称通过 NSImage(named: ...) 获取图像