開源一個 AR 線上項目

線上地址
https://itunes.apple.com/cn/app/weare/id1304227680?mt=8
開源地址
https://github.com/SherlockQi/HeavenMemoirs

WeAre.gif

技術(shù)點

AR初始化

在新建項目時可以直接創(chuàng)建 AR 項目, xcode 會創(chuàng)造一個 AR 項目的模板.

也可以創(chuàng)建普通的項目,在需要實現(xiàn) AR 功能的控制器中實現(xiàn)如下代碼進行初始化.

   import ARKit
   let sceneView = ARSCNView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        sceneView.frame = view.bounds
        view.addSubview(sceneView)

        sceneView.delegate = self
        sceneView.showsStatistics = true
      
        // 創(chuàng)建一個場景,系統(tǒng)默認是沒有的
        let scene = SCNScene()
        sceneView.scene = scene

          //不允許用戶操作攝像機
         sceneView.allowsCameraControl = false
          //抗鋸齒
         sceneView.antialiasingMode = .multisampling4X

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let configuration = ARWorldTrackingConfiguration()
        sceneView.session.run(configuration)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        sceneView.session.pause()
    }

添加節(jié)點

        //我使用的是 SCNPlane 來充當(dāng)相框,也可以使用"厚度"很小的 SCNBox
        let photo = SCNPlane(width: 1, height: 1)
        //photo.cornerRadius = 0.01
        let image = UIImage(named: "0")
        //紋路可以使圖片,也可以是顏色
        photo.firstMaterial?.diffuse.contents = image
        //photo.firstMaterial?.diffuse.contents = UIColor.red
        let photoNode = SCNNode(geometry: photo)
        //節(jié)點的位置
        let vector3 = SCNVector3Make(-1, -1, -1) 
        photoNode.position = vector3
        sceneView.scene.rootNode.addChildNode(photoNode)
         let text = SCNText(string: "文字", extrusionDepth: 0.1)
         text.font = UIFont.systemFont(ofSize: 0.4)
         let textNode = SCNNode(geometry: text)
         textNode.position = SCNVector3Make(0,0, -1)
         //文字的圖片/顏色
         text.firstMaterial?.diffuse.contents = UIImage(named: color)
         sceneView.scene.rootNode.addChildNode(textNode)
可供選擇的幾何圖形
SCNText 文字  
SCNPlane 平面  
SCNBox 盒子  
SCNPyramid 錐形  
SCNSphere 球  
SCNCylinder 圓柱  
SCNCone 圓錐  
SCNTube 圓筒  
SCNCapsule 膠囊  
SCNTorus 圓環(huán)  
SCNFloor 地板  
SCNShape 自定義

全景圖實現(xiàn)

想象自己站在一個球的球心處,球的內(nèi)表面涂著壁畫,那么是不是就實現(xiàn)了全景圖.
所以用一個Sphere 節(jié)點包裹著相機節(jié)點(也就是0位置節(jié)點),再設(shè)置Sphere節(jié)點的內(nèi)表面紋理,就實現(xiàn)了功能.
        let sphere = SCNSphere(radius: 15)
        let sphereNode = SCNNode(geometry: sphere)
        sphere.firstMaterial?.isDoubleSided = true
        sphere.firstMaterial?.diffuse.contents = image
        sphereNode.position = SCNVector3Zero
        scene.rootNode.addChildNode(sphereNode)

播放視頻

            let height:CGFloat = CGFloat(width) * videoSize.height/videoSize.width
            let box = SCNBox(width: width, height: height, length: 0.3, chamferRadius: 0)
            boxNode.geometry = box;
            boxNode.geometry?.firstMaterial?.isDoubleSided = true
            boxNode.position = SCNVector3Make(0, 0, -5);
            box.firstMaterial?.diffuse.contents = UIColor.red
            self.scene.rootNode.addChildNode(boxNode);
            
            
            let avplayer = AVPlayer(url: url)
            avplayer.volume = rescoucceConfiguration.video_isSilence ? 0.0 : 3.0
            videoPlayer = avplayer
            let videoNode = SKVideoNode(avPlayer: avplayer)
            NotificationCenter.default.addObserver(self, selector: #selector(playEnd(notify:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
            
            videoNode.size = CGSize(width: 1600, height: 900)
            videoNode.position = CGPoint(x: videoNode.size.width/2, y: videoNode.size.height/2)
            videoNode.zRotation = CGFloat(Float.pi)
            let skScene = SKScene()
            skScene.addChild(videoNode)
            skScene.size = videoNode.size
            box.firstMaterial?.diffuse.contents = skScene
            videoNode.play()

粒子效果

            /*
              particleName = "bokeh.scnp"
              particleName = "rain.scnp"
              particleName = "confetti.scnp"
            **/
            particleSytem = SCNParticleSystem(named: particleName, inDirectory: nil){
            particleNode.addParticleSystem(particleSytem)
            particleNode.position = SCNVector3Make(0, Y, 0)
            self.scene.rootNode.addChildNode(particleNode)

節(jié)點點擊事件

      //給 場景視圖sceneView 添加點擊事件
       let tap = UITapGestureRecognizer(target: self, action: #selector(tapHandle(gesture:)))
       sceneView.addGestureRecognizer(tap)
  @objc func tapHandle(gesture:UITapGestureRecognizer){
        let results:[SCNHitTestResult] = (self.sceneView?.hitTest(gesture.location(ofTouch: 0, in: self.sceneView), options: nil))!
        guard let firstNode  = results.first else{
            return
        }
        // 這就是點擊到的節(jié)點 可以對他做一些事情 或者根據(jù)這個節(jié)點的某些屬性執(zhí)行不同的方法
        let node = firstNode.node.copy() as! SCNNode
        if firstNode.node == self.selectNode {
            ...推遠照片...
        }else{
            ...拉近照片...
            selectNode = node
        }
    }

節(jié)點動畫

我的另一篇文章中有詳細記錄ARKit-動畫
//拉近(推遠)照片

          //這只是其中一種方法
          let newPosition  = SCNVector3Make(firstNode.node.worldPosition.x*2, firstNode.node.worldPosition.y*2, firstNode.node.worldPosition.z*2)
          let comeOut = SCNAction.move(to: newPosition, duration: 1.2)
          firstNode.node.runAction(comeOut)

自傳/公轉(zhuǎn)

            //自轉(zhuǎn)
            let box = SCNBox(width: boxW, height: boxW, length: boxW, chamferRadius: 0)
            let boxNode = SCNNode(geometry: box)
            boxNode.position = vector3
            let emptyNode = SCNNode()
            emptyNode.position = SCNVector3Zero
            emptyNode.rotation = SCNVector4Make(0, 1, 0, Float.pi/Float(L/2) * Float(index))
            emptyNode.addChildNode(boxNode)
            photoRingNode.addChildNode(emptyNode)
            let ringAction = SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: right, z: 0, duration: 2))
            boxNode.runAction(ringAction)
            //公轉(zhuǎn) 把節(jié)點加到一個正在自傳的節(jié)點上就可以了

錄屏

錄屏是使用ReplayKit完成的
開始錄屏

    協(xié)議      
    RPScreenRecorderDelegate,RPPreviewViewControllerDelegate

     RPScreenRecorder.shared().startRecording(handler: nil)
     RPScreenRecorder.shared().delegate = self

錄制代理

func screenRecorder(_ screenRecorder: RPScreenRecorder, didStopRecordingWith previewViewController: RPPreviewViewController?, error: Error?) {
        print(error ?? "error")
        if error != nil{
            print("error:", error ?? "")
            DispatchQueue.main.async {
                let string = error?.localizedDescription
                ITTPromptView .showMessage(string, andFrameY: 0)
                print(string ?? "")
                //錄制期間失敗
                self.showFailReplay()
            }
        }else{
            print("else")
        }
        print("start recording handler")
    }
    //錄制失敗
    func showFailReplay(){
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: "HKExplainViewController")
        self.navigationController?.pushViewController(vc, animated: true)
        self.replayButtonRight.constant = 85;
        for button in self.smailButtons {
            button.alpha = 1
        }
        self.mainButton.alpha = 1
        UIView.animate(withDuration: 2.5) {
            self.stopReplayButton.alpha = 0
            self.view.layoutIfNeeded()
        }
    }

結(jié)束并彈出預(yù)覽控制器

      RPScreenRecorder.shared().stopRecording { (vc, erroe) in
            vc?.previewControllerDelegate = self
            vc?.title = "We Are"
            self.present(vc!, animated: true, completion: nil)
        }

預(yù)覽控制器的代理

    func previewController(_ previewController: RPPreviewViewController, didFinishWithActivityTypes activityTypes: Set<String>) {
        print(activityTypes)
        //取消
        if activityTypes.count == 0 {
            previewController.dismiss(animated: true, completion: nil)
        }
        //保存
        if activityTypes.contains("com.apple.UIKit.activity.SaveToCameraRoll"){
            ITTPromptView .showMessage("視頻已保存在相冊", andFrameY: 0)
            previewController.dismiss(animated: true, completion: nil)
            //檢測到您剛剛保存了視頻 是否想要分享
            let delay = DispatchTime.now() + .seconds(2)
            DispatchQueue.main.asyncAfter(deadline: delay) {
                self.outputVideo()
            }
        }
    }

目前所有代碼已上傳至 github https://github.com/SherlockQi/HeavenMemoirs
歡迎(跪求)Star!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,172評論 3 119
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,067評論 4 61
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,781評論 25 709
  • 二超四月/ 1 《歲月里的故事》 歲月有無心 當(dāng)知季節(jié)變幻 可知我曾愛你 2 《入》 喝過的酒進入肚子里 流過的淚...
    二超四月閱讀 257評論 2 2
  • 春天尚未開始 夏天已經(jīng)結(jié)束 在一個寧靜的夜晚 我看到你寫在黑暗中的訣別詩 你即將遠行 踏上征程 前方的歌聲凄厲而陰...
    半島公子閱讀 559評論 2 9

友情鏈接更多精彩內(nèi)容