ios arkit_iOS ARKit教程–增强现实iOS应用

本文引导开发者使用ARKit和SceneKit创建第一个增强现实iOS应用。介绍了ARKit的基础知识,包括如何开始iOS ARKit项目,理解3D模型格式,以及如何修改模型的规模和位置。此外,还展示了如何添加SCNBox和改变其背景颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ios arkit

In this tutorial, we’ll be developing our first Augmented Reality iOS Application using ARKit and SceneKit.

在本教程中,我们将使用ARKit和SceneKit开发第一个增强现实iOS应用程序。

Pre-requisites: 先决条件:
  • XCode 9 or above

    XCode 9或以上
  • iPhone 6s or above since ArKit requires A9 processor.

    iPhone 6s或更高版本,因为ArKit需要A9处理器。
  • iOS 11 or above.

    iOS 11或更高版本。

ARKit简介 (Introduction to ARKit)

  • ARKit library was introduced by Apple in WWDC 2017.

    Apple在WWDC 2017中引入了ARKit库。
  • It allows developers to build Augmented Reality Applications.

    它允许开发人员构建增强现实应用程序。
  • Augmented Reality Applications allows us to view virtual objects in the real environment through the camera.

    增强现实应用程序使我们可以通过相机在真实环境中查看虚拟对象。
  • Augmented Reality is like a mixture of Virtual Reality and the Real World.

    增强现实就像虚拟现实和现实世界的混合体。
  • We can place either 2D or 3D objects in the ARKit scene. For 2D objects, SpriteKit iOS library is used. For 3D objects, SceneKit is used.

    我们可以在ARKit场景中放置2D或3D对象。 对于2D对象,使用SpriteKit iOS库。 对于3D对象,使用SceneKit。

The basic Augmented Reality iOS app that we’ll be building next will use SceneKit.

接下来要构建的基本增强现实iOS应用将使用SceneKit。

3D Models are of the format DAE and SCN.

3D模型的格式为DAESCN

We can create a customize 3D models using the free Blender Software.

我们可以使用免费的Blender软件创建自定义3D模型。

Let’s get started with the development now.

现在开始开发。

iOS ARKit入门 (Getting Started with iOS ARKit)

Launch your XCode and create a new project. Make sure that you’ve selected the template as Augmented Reality App for this tutorial.

启动您的XCode并创建一个新项目。 确保已为本教程选择了模板作为“增强现实应用程序”。

On the next screen, ensure that you’ve selected SceneKit.

在下一个屏幕上,确保已选择SceneKit。

Now XCode creates your first ARKit project.

现在,XCode创建您的第一个ARKit项目。

iOS ARKit教程项目结构 (iOS ARKit Tutorial Project Structure)

There’s a ship.scn 3D sample model created.

创建了一个ship.scn 3D样本模型。

The 3D model is some distance away from the origin. This can be altered from the attributes panel on the right side.

3D模型离原点有些距离。 可以从右侧的属性面板更改此设置。

On MainStoryboard has the SceneView already linked to the ViewController.

在MainStoryboard上,SceneView已链接到ViewController。

The ViewController.swift has a boilerplate code in place to set the scn file and begin the AR tracking.

ViewController.swift有一个样板代码,用于设置scn文件并开始AR跟踪。

Let’s run this sample Augmented Reality App on a device.

让我们在设备上运行此示例增强现实应用程序。

On clicking run, you might get the following dialog in your XCode.

ios arkit verify app

单击运行时,您可能会在XCode中获得以下对话框。

After trusting the app from the settings following is the output of the application:

从设置信任应用程序之后,以下是应用程序的输出:

WOW! The ship 3D model is displayed on the screen.

哇! 屏幕上显示了船用3D模型。

But where is the origin? How can we change the size and position of the ship? How are the stats at the bottom being displayed? How do we add another 3D object on the Scene?

但是起源在哪里? 我们如何改变船舶的大小和位置? 底部的统计数据如何显示? 我们如何在场景上添加另一个3D对象?

We’ll be discussing each of these in the next section where we’ll play around with the Swift code as well.

我们将在下一节中讨论其中的每一个,同时我们还将介绍Swift代码。

The default code for the ViewController.swift is given below:

ios arkit viewcontroller default code

下面给出了ViewController.swift的默认代码:

The ARSCNView class is the view used for displaying 3D objects in the AR SceneView. The ViewController class conforms to the protocol ARSCNViewDelegate.

ARSCNView类是用于在AR SceneView中显示3D对象的视图。 ViewController类符合协议ARSCNViewDelegate。

sceneView.showsStatistics = true is used to show the stats i.e. fps etc at the bottom of the screen.

sceneView.showsStatistics = true用于在屏幕底部显示统计信息,例如fps等。

sceneView.session returns an ARSession. On this, we run our AR tracking by setting the configuration in the run method.

sceneView.session返回一个ARSession。 在此基础上,我们通过在run方法中设置配置来运行AR跟踪。

修改模型的比例和位置 (Modifying the scale and position of the Model)

We can modify the scale and position of the Model (ship in this case) in the following way:

我们可以通过以下方式修改Model(在这种情况下为船)的比例尺和位置:

The Position of the model is the position of the SCNNode relative to the camera.

模型的位置是SCNNode相对于摄像机的位置。

Positive x is to the right. Negative x is to the left.

正数x在右边。 负x在左边。

Positive y is up. Negative y is down.

y为正。 负y下降。

Positive z is backward. Negative z is forward.

正数z向后。 负z是正向。

iOS ARKit SCN Attributes

Changing scale to make the model appear shorter

更改比例以使模型显得更短

In the above example, we’ve set the scn model to the origin.

在上面的示例中,我们将scn模型设置为原点。

添加一个SCNBox (Adding an SCNBox)

Let’s add an SCNBox in our ViewController.swift below:

让我们在下面的ViewController.swift中添加一个SCNBox:

import UIKit
import SceneKit
import ARKit

class ViewController: UIViewController, ARSCNViewDelegate {

@IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set the view's delegate
        sceneView.delegate = self
        
        // Show statistics such as fps and timing information
        sceneView.showsStatistics = true
        sceneView.debugOptions = ARSCNDebugOptions.showWorldOrigin
        
        // Create a new scene
        let scene = SCNScene(named: "art.scnassets/ship.scn")!
        
        // Set the scene to the view
        sceneView.scene = scene
        addBox()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // Create a session configuration
        let configuration = ARWorldTrackingConfiguration()

        // Run the view's session
        sceneView.session.run(configuration)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // Pause the view's session
        sceneView.session.pause()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Release any cached data, images, etc that aren't in use.
    }

    // MARK: - ARSCNViewDelegate
    
/*
    // Override to create and configure nodes for anchors added to the view's session.
    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        let node = SCNNode()
     
        return node
    }
*/
    
    func session(_ session: ARSession, didFailWithError error: Error) {
        // Present an error message to the user
        
    }
    
    func sessionWasInterrupted(_ session: ARSession) {
        // Inform the user that the session has been interrupted, for example, by presenting an overlay
        
    }
    
    func sessionInterruptionEnded(_ session: ARSession) {
        // Reset tracking and/or remove existing anchors if consistent tracking is required
        
    }
    
    func addBox() {
        let box = SCNBox(width: 0.05, height: 0.05, length: 0.05, chamferRadius: 0)
        
        let boxNode = SCNNode()
        boxNode.geometry = box
        boxNode.position = SCNVector3(0, 0, -0.2)
        sceneView.scene.rootNode.addChildNode(boxNode)
    }
}

sceneView.debugOptions = ARSCNDebugOptions.showWorldOrigin is used to show the origin and the coordinate lines in the camera scene.

sceneView.debugOptions = ARSCNDebugOptions.showWorldOrigin用于显示摄像机场景中的原点和坐标线。

In the addBox() function we add a SCNNode of the shape box to our Scene in the ARSCNView.

在addBox()函数中,将形状框的SCNNode添加到ARSCNView中的场景中。

The output when the above application is run is given below:

运行上述应用程序时的输出如下:

So our SCNBox is set in front of the origin and is colored white.

因此,我们的SCNBox设置在原点的前面,并显示为白色。

更改SCNBox的背景颜色 (Changing the background color of the SCNBox)

SCNNode above is like a SCNBox and has six sides. Lets set a different color on each side.

上面的SCNNode就像一个SCNBox,具有六个侧面。 让我们在每侧设置不同的颜色。

Change the addBox() method to the following:

将addBox()方法更改为以下内容:

func addBox() {
        let box = SCNBox(width: 0.05, height: 0.05, length: 0.05, chamferRadius: 0)
        
        let boxNode = SCNNode()
        boxNode.geometry = box
        boxNode.position = SCNVector3(0, 0, -0.2)
        
        let colors = [UIColor.green, // front
            UIColor.red, // right
            UIColor.blue, // back
            UIColor.yellow, // left
            UIColor.purple, // top
            UIColor.gray] // bottom
        
        let sideMaterials = colors.map { color -> SCNMaterial in
            let material = SCNMaterial()
            material.diffuse.contents = color
            material.locksAmbientWithDiffuse = true
            return material
        }
        boxNode.geometry?.materials = sideMaterials
        sceneView.scene.rootNode.addChildNode(boxNode)
    }

We use the materials property on the box and set a different UI Color from the array on each side by mapping them to the respecitve SCNMaterial.

我们使用盒子上的materials属性,并通过将它们映射到指定的SCNMaterial,从每一面的数组设置不同的UI颜色。

The output of the application in action is given below. All the sides have a different color.

实际应用程序的输出如下。 所有侧面都有不同的颜色。

This brings an end to this ARKit Tutorial. You can download the project from the link below:

这结束了本ARKit教程。 您可以从下面的链接下载项目:

Reference: ARKit Docs

参考: ARKit文档

翻译自: https://www.journaldev.com/21584/ios-arkit-tutorial-augmented-reality-app

ios arkit

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值