Not able to add texture image to a cube in ARKit

2019-04-17 07:21发布

问题:

I am not able to add an image to the cube in ARKit using the "Material" object.

Here is the code:

import UIKit
import SceneKit
import ARKit

class SimpleBoxViewController: UIViewController, ARSCNViewDelegate {

var sceneView: ARSCNView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.sceneView = ARSCNView(frame: self.view.frame)
    self.view.addSubview(self.sceneView)

    sceneView.delegate = self
    sceneView.showsStatistics = true

    let scene = SCNScene()

    let box = SCNBox(width: 0.2, height: 0.2, length: 0.2, chamferRadius: 0)

    let material = SCNMaterial() 

    //This is not working
    material.diffuse.contents = UIImage(named: "<someImage>.png")

    let node = SCNNode() 
    node.geometry = box
    node.geometry?.materials = [material]
    node.position = SCNVector3(0, -0.1, -0.5)
    scene.rootNode.addChildNode(node)

    sceneView.scene = scene


}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let configuration = ARWorldTrackingConfiguration()
    sceneView.session.run(configuration)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    // Pause the view's session
    sceneView.session.pause()
}

I tried to add various different images but nothing works. The only image that works is the image named "textures.png" which is preloaded into an ARKit project.

Is there a specific requirement for an image to be to loaded?

回答1:

I'm not 100% sure on this one, but the issue might be with including the .png with the imageName, since this image should be in your Assets folder.

Anyway, this code is working for me and tries do to the same thing with regards to creating the cube with an image.

var box = SCNBox(width: pd.width, height: pd.height, length: 0.01,
chamferRadius: 0.0)
var imageMaterial = SCNMaterial()
var image = UIImage(named: "image")
imageMaterial.diffuse.contents = image
box.materials = [imageMaterial, imageMaterial, imageMaterial, imageMaterial, imageMaterial, imageMaterial]
var cube = SCNNode(geometry: box)


回答2:

you have to add the path like:

 material.diffuse.contents = UIImage(named: "art.scnassets/textur")

this works for me.



回答3:

I was also facing the same issue. I have copied the png files into Assets.xcassets folder and its works for me.