首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在CVPixelBuffer中使用Swift绘制/编辑iOS的正确方法

在CVPixelBuffer中使用Swift绘制/编辑iOS的正确方法
EN

Stack Overflow用户
提问于 2022-03-18 02:15:51
回答 1查看 830关注 0票数 1

是否有标准的执行方式来编辑/绘制CVImageBuffer/CVPixelBuffer?

我在网上找到的所有视频编辑演示都覆盖了屏幕上的绘图(矩形或文本),并且不直接编辑CVPixelBuffer。

我尝试使用CGContext更新,但是保存的视频没有显示上下文绘图

代码语言:javascript
运行
复制
private var adapter: AVAssetWriterInputPixelBufferAdaptor?

extension TrainViewController: CameraFeedManagerDelegate {
    
    func didOutput(sampleBuffer: CMSampleBuffer) {

        let time = CMTime(seconds: timestamp - _time, preferredTimescale: CMTimeScale(600))
        let pixelBuffer: CVPixelBuffer? = CMSampleBufferGetImageBuffer(sampleBuffer)

        guard let context = CGContext(data: CVPixelBufferGetBaseAddress(pixelBuffer),
                                  width: width,
                                  height: height,
                                  bitsPerComponent: 8,
                                  bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer),
                                  space: colorSpace,
                                  bitmapInfo: alphaInfo.rawValue)
        else {
          return nil
        }

        context.setFillColor(red: 1, green: 0, blue: 0, alpha: 1.0)
        context.fillEllipse(in: CGRect(x: 0, y: 0, width: width, height: height))
        context.flush()

        adapter?.append(pixelBuffer, withPresentationTime: time)


    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-02 20:49:37

在绘制完上下文后,您需要在创建位图CVPixelBufferLockBaseAddress(pixelBuffer, 0)CGContextCVPixelBufferUnlockBaseAddress(pixelBuffer, 0)之前调用CVPixelBufferUnlockBaseAddress(pixelBuffer, 0)

在不锁定像素缓冲区的情况下,CVPixelBufferGetBaseAddress()返回空。这将导致您的CGContext分配新的内存,然后将其丢弃。

同时还要检查你的颜色空间。很容易把你的部件混在一起。

例如:

代码语言:javascript
运行
复制
guard
    CVPixelBufferLockBaseAddress(pixelBuffer) == kCVReturnSuccess,
    let context = CGContext(data: CVPixelBufferGetBaseAddress(pixelBuffer),
                            width: width,
                            height: height,
                            bitsPerComponent: 8,
                            bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer),
                            space: colorSpace,
                            bitmapInfo: alphaInfo.rawValue)
else {
    return nil
}

context.setFillColor(red: 1, green: 0, blue: 0, alpha: 1.0)
context.fillEllipse(in: CGRect(x: 0, y: 0, width: width, height: height))

CVPixelBufferUnlockBaseAddress(pixelBuffer)

adapter?.append(pixelBuffer, withPresentationTime: time)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71521769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档