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

如何在macOS中通过AVCaptureDevice设置摄像头变焦?

macOS下基于AVFoundation实现摄像头变焦方案

核心思路

macOS的AVCaptureDevice虽没有和iOS完全同名的videoZoomFactor属性,但在macOS 10.15及以上系统中,已经支持硬件级变焦API,操作逻辑和iOS类似,只需先做设备兼容性校验。

步骤实现

1. 检查设备变焦支持性

先获取目标摄像头设备,确认它支持变焦功能:

import AVFoundation

// 根据需求调整position参数,切换前置/后置摄像头
guard let cameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) else {
    print("未检测到可用摄像头")
    return
}

// 确认硬件变焦支持性,以及当前格式下的最大变焦系数
let canZoom = cameraDevice.isVideoZoomSupported
let maxZoomFactor = cameraDevice.activeFormat.videoMaxZoomFactor

2. 直接设置固定变焦系数

如果需要一次性切换到目标变焦倍数,直接操作videoZoomFactor即可:

do {
    // 修改设备参数前必须先锁定配置
    try cameraDevice.lockForConfiguration()
    
    if canZoom, let maxZoom = cameraDevice.activeFormat.videoMaxZoomFactor {
        let targetZoom: CGFloat = 2.0 // 目标2倍变焦
        // 确保目标系数在1.0(原始画面)到最大变焦范围之间
        if targetZoom >= 1.0 && targetZoom <= maxZoom {
            cameraDevice.videoZoomFactor = targetZoom
        }
    }
    
    // 操作完成后解锁配置
    cameraDevice.unlockForConfiguration()
} catch {
    print("修改变焦参数失败:\(error.localizedDescription)")
}

3. 平滑过渡变焦

如果需要类似“拉镜头”的平滑变焦效果,使用ramp(toVideoZoomFactor:withRate:)方法:

do {
    try cameraDevice.lockForConfiguration()
    
    if cameraDevice.isVideoRampingSupported, let maxZoom = cameraDevice.activeFormat.videoMaxZoomFactor {
        let targetZoom: CGFloat = 3.0
        if targetZoom >= 1.0 && targetZoom <= maxZoom {
            // rate参数控制变焦速度,数值越大变焦越快
            cameraDevice.ramp(toVideoZoomFactor: targetZoom, withRate: 2.0)
        }
    }
    
    cameraDevice.unlockForConfiguration()
} catch {
    print("平滑变焦失败:\(error.localizedDescription)")
}

兼容性 fallback(旧系统/不支持硬件变焦的设备)

如果应用需要兼容macOS 10.15以下版本,或遇到不支持硬件变焦的外接摄像头,可以通过AVCaptureVideoPreviewLayer的仿射变换实现视觉缩放(注意:这是软件级缩放,会损失画质):

// 假设已创建AVCaptureSession并完成输入输出配置
let previewLayer = AVCaptureVideoPreviewLayer(session: yourCaptureSession)
// 设置2倍视觉放大的变换
let scaleTransform = CGAffineTransform(scaleX: 2.0, y: 2.0)
previewLayer.setAffineTransform(scaleTransform)

注意事项

  • 所有设备参数修改必须在lockForConfiguration()和unlockForConfiguration()之间执行,否则会抛出错误
  • 不同摄像头的最大变焦系数不同,务必以activeFormat.videoMaxZoomFactor返回值为准,不要硬编码数值
  • 外接摄像头可能不支持硬件变焦,需要提前做判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:15:44