【iOS11 ARKit】iPhoneの写真をテクスチャにして貼ってみた

ARKitを使って、立方体にテクスチャを貼ってみました。

貼った画像はiPhone内の写真のライブラリから読み込んでいます。

var photoAssets = [PHAsset]()
var imgAssets = [UIImage]()

override func viewDidLoad() {
    super.viewDidLoad()

    sceneView.delegate = self

    sceneView.showsStatistics = true

    let scene = SCNScene()

    photoAssets = []

    let m1 = SCNMaterial()
    let m2 = SCNMaterial()
    let m3 = SCNMaterial()
    let m4 = SCNMaterial()
    let m5 = SCNMaterial()
    let m6 = SCNMaterial()

    // ソート条件を指定
    let options = PHFetchOptions()
    options.sortDescriptors = [
        NSSortDescriptor(key: "creationDate", ascending: false)
    ]

    // 画像をすべて取得
    let assets: PHFetchResult = PHAsset.fetchAssets(with: .image, options: nil)
    assets.enumerateObjects { (asset, index, stop) -> Void in
        self.photoAssets.append(asset as PHAsset)

        let manager: PHImageManager = PHImageManager()
        manager.requestImage(for: asset,
                                     targetSize: CGSize(width: 100, height: 100),
                                     contentMode: .aspectFill,
                                     options: nil) { (image, info) -> Void in

                                        self.imgAssets.append(image!)

        }

    }

    //print(photoAssets)

    m1.diffuse.contents = self.imgAssets[0]
    m2.diffuse.contents = self.imgAssets[1]
    m3.diffuse.contents = self.imgAssets[2]
    m4.diffuse.contents = self.imgAssets[3]
    m5.diffuse.contents = self.imgAssets[4]
    m6.diffuse.contents = self.imgAssets[5]

    let cube = SCNBox(width: 0.2, height: 0.2, length: 0.2, chamferRadius: 0)
    let cubeNode2 = SCNNode(geometry: cube)

    let material2 = SCNMaterial()
    material2.diffuse.contents = UIColor.white
    cubeNode2.geometry?.firstMaterial = material2

    cubeNode2.position = SCNVector3Make(0, -0.2, -0.5);

    cube.materials = [m1, m2, m3, m4, m5, m6]

    scene.rootNode.addChildNode(cubeNode2)

    // Set the scene to the view
    sceneView.scene = scene

参考記事