You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ARKit(Swift4)中为AR视图添加黑白滤镜?

Convert ARKit View to Black-and-White with Filtered Screenshots

Hey there! To turn your ARKit view into a black-and-white display (and ensure screenshots capture the filtered look), using SceneKit's SCNTechnique is the most efficient way—it leverages GPU acceleration for real-time post-processing, and your screenshots will automatically include the filter. Here's a complete implementation:

Step-by-Step Implementation

  1. First, make sure to import CoreImage (we'll use its built-in black-and-white filter).
  2. Define a SCNTechnique that applies the CIPhotoEffectMono filter to every frame rendered by SceneKit.
  3. Attach the technique to your AR scene, and use the standard snapshot() method to capture filtered images.

Full Code

import UIKit
import SceneKit
import ARKit
import CoreImage // Required for Core Image filters

class ViewController: UIViewController, ARSCNViewDelegate {
    @IBOutlet var sceneView: ARSCNView!
    
    // Stores our black-and-white post-processing technique
    private var blackAndWhiteTechnique: SCNTechnique?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        sceneView.delegate = self
        sceneView.showsStatistics = true
        
        // Initialize and run AR session
        let configuration = ARWorldTrackingConfiguration()
        sceneView.session.run(configuration)
        
        // Set up the black-and-white filter technique
        setupBlackAndWhitePostProcessing()
    }
    
    private func setupBlackAndWhitePostProcessing() {
        // JSON configuration for the SceneKit technique
        let techniqueConfig = """
        {
            "passes": {
                "monoPass": {
                    "outputs": { "color": "COLOR" },
                    "inputs": { "color": "COLOR" },
                    "filter": "CIPhotoEffectMono"
                }
            },
            "sequence": ["monoPass"],
            "drawables": ["color"]
        }
        """
        
        // Parse the JSON into a SCNTechnique
        guard let configData = techniqueConfig.data(using: .utf8),
              let technique = try? SCNTechnique(data: configData) else {
            print("Failed to initialize black-and-white technique")
            return
        }
        
        blackAndWhiteTechnique = technique
        // Apply the technique to the AR scene
        sceneView.scene.technique = blackAndWhiteTechnique
    }
    
    // Example: Take a filtered screenshot (connect this to a UIButton)
    @IBAction func captureScreenshot(_ sender: UIButton) {
        let filteredScreenshot = sceneView.snapshot()
        // Save screenshot to photo library
        UIImageWriteToSavedPhotosAlbum(filteredScreenshot, self, #selector(saveCompletionHandler(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    @objc private func saveCompletionHandler(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            print("Screenshot save failed: \(error.localizedDescription)")
        } else {
            print("Filtered screenshot saved successfully!")
        }
    }
    
    // Optional: Handle AR session errors
    func session(_ session: ARSession, didFailWithError error: Error) {
        print("AR session encountered an error: \(error.localizedDescription)")
    }
}

Key Notes

  • Real-Time Filter: The SCNTechnique integrates directly with SceneKit's rendering pipeline, so the black-and-white effect is applied instantly to every frame without lag.
  • Filtered Screenshots: Calling sceneView.snapshot() will capture the exact view displayed (including the filter) — no extra processing needed for screenshots.
  • Toggle Effect: If you want to switch between color and black-and-white later, just set sceneView.scene.technique = nil to disable the filter, or reassign blackAndWhiteTechnique to enable it again.

内容的提问来源于stack exchange,提问作者user8105388

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:55:50