帮助您实现目标的最佳方法是使用Metal
框架。使用Metal
相机有助于最大限度地减少对设备有限计算资源的影响。如果您试图以最低的开销访问相机传感器,那么使用 aAVCaptureSession
将是一个非常好的开始。
您需要从CMSampleBuffer
(您是对的)获取每个帧数据,然后将帧转换为MTLTexture
. AVCaptureSession
将通过委托回调不断地从设备的相机向我们发送帧。
所有可用的叠加层也必须转换为MTLTextures
。然后您可以使用操作合成所有MTLTextures
图层over
。
因此,在这里您可以找到四部分 金属相机 系列的所有必要信息。
这里有一个博客链接:关于金属合成。
另外,我想发布代码摘录(在 Metal 中使用 AVCaptureSession):
import Metal
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
// Handle an error here.
}
// Texture cache for converting frame images to textures
var textureCache: CVMetalTextureCache?
// `MTLDevice` for initializing texture cache
var metalDevice = MTLCreateSystemDefaultDevice()
guard
let metalDevice = metalDevice
where CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, metalDevice, nil, &textureCache) == kCVReturnSuccess
else {
// Handle an error (failed to create texture cache)
}
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
var imageTexture: CVMetalTexture?
let result = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache.takeUnretainedValue(), imageBuffer, nil, pixelFormat, width, height, planeIndex, &imageTexture)
// `MTLTexture` is in the `texture` variable now.
guard
let unwrappedImageTexture = imageTexture,
let texture = CVMetalTextureGetTexture(unwrappedImageTexture),
result == kCVReturnSuccess
else {
throw MetalCameraSessionError.failedToCreateTextureFromImage
}
在这里,您可以在 GitHub 上找到最终项目:MetalRenderCamera