gpt4 book ai didi

ios - 视频预览的自定义形状 : AVCaptureVideoPreviewLayer?

转载 作者:行者123 更新时间:2023-11-29 13:52:32 27 4
gpt4 key购买 nike

是否可以像裁剪图像一样裁剪视频预览层?

    image
.clipShape(Circle())
.overlay(Circle().stroke(Color.green, lineWidth: 1))

视频预览层来自哪里:

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = CGRect(x: 20, y: 60, width: 335, height: 200)
previewLayer.videoGravity = .resizeAspectFill
view.layer.addSublayer(previewLayer)

我一直在寻找,但没有找到。谢谢!

最佳答案

在 macOS 10.15 Catalina 上测试

下面的演示代码是针对 SwiftUI/macOS 的,但它可能会有所帮助,因为只需对代码进行少量更改即可使其与 iOS 保持一致。

注意:这是一个演示,所以代码有点乱

结果如下:

masked video capture from SwiftUI

这是演示模块代码:

import SwiftUI
import AppKit
import AVFoundation

class PreviewView: NSView {
private var captureSession: AVCaptureSession?

init() {
super.init(frame: .zero)

var allowedAccess = false
let blocker = DispatchGroup()
blocker.enter()
AVCaptureDevice.requestAccess(for: .video) { flag in
allowedAccess = flag
blocker.leave()
}
blocker.wait()

if !allowedAccess {
print("!!! NO ACCESS TO CAMERA")
return
}

// setup session
let session = AVCaptureSession()
session.beginConfiguration()

// this part might be different in iOS
let videoDevice = AVCaptureDevice.default(for: .video)

guard let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice!),
session.canAddInput(videoDeviceInput)
else { return }
session.addInput(videoDeviceInput)
session.commitConfiguration()
self.captureSession = session

// instead of below, use layerClass on iOS
self.wantsLayer = true
self.layer = AVCaptureVideoPreviewLayer()
}

required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

var videoPreviewLayer: AVCaptureVideoPreviewLayer {
return layer as! AVCaptureVideoPreviewLayer
}

override func viewDidMoveToSuperview() { // on iOS .didMoveToSuperview
super.viewDidMoveToSuperview()

if nil != self.superview {
self.videoPreviewLayer.session = self.captureSession
self.videoPreviewLayer.videoGravity = .resizeAspect
self.captureSession?.startRunning()
} else {
self.captureSession?.stopRunning()
}
}
}

// for iOS NSView just rename to UIView
struct PreviewHolder: NSViewRepresentable {
func makeNSView(context: NSViewRepresentableContext<PreviewHolder>) -> PreviewView {
PreviewView()
}

func updateNSView(_ uiView: PreviewView, context: NSViewRepresentableContext<PreviewHolder>) {
}

typealias NSViewType = PreviewView
}

struct DemoPreviewLayer: View {
var body: some View {
VStack {
PreviewHolder()
.mask(Circle())
}.frame(width: 400, height: 300)
}
}

struct DemoPreviewLayer_Previews: PreviewProvider {
static var previews: some View {
DemoPreviewLayer()
}
}

关于ios - 视频预览的自定义形状 : AVCaptureVideoPreviewLayer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58931747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com