开源一个 AR 线上项目

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

WeAre.gif

技术点

AR初始化

在新建项目时可以直接创建 AR 项目, xcode 会创造一个 AR 项目的模板.

也可以创建普通的项目,在需要实现 AR 功能的控制器中实现如下代码进行初始化.

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

        sceneView.delegate = self
        sceneView.showsStatistics = true
      
        // 创建一个场景,系统默认是没有的
        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()
    }

添加节点

        //我使用的是 SCNPlane 来充当相框,也可以使用"厚度"很小的 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)
        //节点的位置
        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 圆环  
SCNFloor 地板  
SCNShape 自定义

全景图实现

想象自己站在一个球的球心处,球的内表面涂着壁画,那么是不是就实现了全景图.
所以用一个Sphere 节点包裹着相机节点(也就是0位置节点),再设置Sphere节点的内表面纹理,就实现了功能.
        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)

节点点击事件

      //给 场景视图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
        }
        // 这就是点击到的节点 可以对他做一些事情 或者根据这个节点的某些属性执行不同的方法
        let node = firstNode.node.copy() as! SCNNode
        if firstNode.node == self.selectNode {
            ...推远照片...
        }else{
            ...拉近照片...
            selectNode = node
        }
    }

节点动画

我的另一篇文章中有详细记录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)

自传/公转

            //自转
            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)
            //公转 把节点加到一个正在自传的节点上就可以了

录屏

录屏是使用ReplayKit完成的
开始录屏

    协议      
    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()
        }
    }

结束并弹出预览控制器

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

预览控制器的代理

    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!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,937评论 3 118
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,616评论 4 59
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • 二超四月/ 1 《岁月里的故事》 岁月有无心 当知季节变幻 可知我曾爱你 2 《入》 喝过的酒进入肚子里 流过的泪...
    二超四月阅读 218评论 2 2
  • 春天尚未开始 夏天已经结束 在一个宁静的夜晚 我看到你写在黑暗中的诀别诗 你即将远行 踏上征程 前方的歌声凄厉而阴...
    半岛公子阅读 501评论 2 9