本demo主要功能是創(chuàng)建一個(gè)把虛擬的畫掛在墻上:
語言:Swift
效果圖:
IMG_0209.PNG
注意3點(diǎn) : 需要iPhone6s及以上手機(jī) ,至少iOS 11以上系統(tǒng), 必須真機(jī)運(yùn)行
主要是代碼和注釋 部分如下 下載 Demo:
1 引入頭文件
//引入ARkit所需的包
import ARKit
//引入 SceneKit
import SceneKit
2 代理和屬性
class ArtTreeViewController: UIViewController,ARSCNViewDelegate {
//必備
let arSCNView = ARSCNView()
let arSession = ARSession()
let arConfiguration = ARWorldTrackingConfiguration()
//用來顯示圖的節(jié)點(diǎn)
let ArtPicNode = SCNNode()
.........
}
3.設(shè)置顯示場景的背景view
//設(shè)置arSCNView屬性
arSCNView.frame = self.view.frame
arSCNView.session = arSession
arSCNView.automaticallyUpdatesLighting = true//自動(dòng)調(diào)節(jié)亮度
self.view.addSubview(arSCNView)
arSCNView.delegate = self
4.創(chuàng)建一個(gè)長方體,并把圖片覆蓋到其表面
//創(chuàng)建一個(gè)長方體,用來展示圖片
ArtPicNode.geometry = SCNBox.init(width: boxW, height: boxH, length: boxL, chamferRadius: 0.1) //方形
//把圖片覆蓋到其表面
ArtPicNode.geometry?.firstMaterial?.diffuse.contents = timgKuang.jpg
ArtPicNode.geometry?.firstMaterial?.multiply.intensity = 0.5 //強(qiáng)度
ArtPicNode.geometry?.firstMaterial?.lightingModel = SCNMaterial.LightingModel.constant
//3.設(shè)置位置:相對于攝像頭
ArtPicNode.position = SCNVector3(0, 5, -20)
//添加長方體到界面上
self.arSCNView.scene.rootNode.addChildNode(ArtPicNode)