swift - 修改 CVPixelBuffer
问题描述
我正在使用下面的方法将绘图添加到像素缓冲区,然后将其附加到AVAssetWriterInputPixelBufferAdaptor
.
它适用于我的 Mac mini(macOS 12 beta 7),但drawingHandler
在我的 MacBook(macOS 11.5.2)上没有任何效果。
这段代码有什么问题吗?
#if os(macOS)
import AppKit
#else
import UIKit
#endif
import CoreMedia
extension CMSampleBuffer {
func pixelBuffer(drawingHandler: ((CGRect) -> Void)? = nil) -> CVPixelBuffer? {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(self) else {
return nil
}
guard let drawingHandler = drawingHandler else {
return pixelBuffer
}
guard CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly) == kCVReturnSuccess else {
return pixelBuffer
}
let data = CVPixelBufferGetBaseAddress(pixelBuffer)
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
let bitsPerComponent = 8
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let imageByteOrderInfo = CGImageByteOrderInfo.order32Little
let imageAlphaInfo = CGImageAlphaInfo.premultipliedFirst
if let ctx = CGContext(data: data,
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: imageByteOrderInfo.rawValue | imageAlphaInfo.rawValue)
{
// Push
#if os(macOS)
let graphCtx = NSGraphicsContext(cgContext: ctx, flipped: false)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = graphCtx
#else
UIGraphicsPushContext(ctx)
#endif
let rect = CGRect(x: 0, y: 0, width: width, height: height)
drawingHandler(rect)
// Pop
#if os(macOS)
NSGraphicsContext.restoreGraphicsState()
#else
UIGraphicsPopContext()
#endif
}
CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly)
return pixelBuffer
}
}
解决方案
更改锁定标志。
let lockFlags = CVPixelBufferLockFlags(rawValue: 0)
guard CVPixelBufferLockBaseAddress(pixelBuffer, lockFlags) == kCVReturnSuccess else {
return pixelBuffer
}
// ...
CVPixelBufferUnlockBaseAddress(pixelBuffer, lockFlags)
推荐阅读
- javascript - 使用 jQuery 在输入上触发按键
- python - 错误:'value':keys_to_typing(value)} 发送密钥 selenium python
- javascript - 如何基于诸如 java 包之类的键将数组转换为 JSON 以查看树视图
- reactjs - 在 react-testing-library 中按 id 查找元素
- sql-server - 使用列自己的输出作为输入计算 SQL 中的列
- sql-server - SQL Server 中的 TableDiff 错误?
- java - Selenium - 错误:表达式不是 xpath 的合法表达式
- spring - Spring Boot 中休息控制器的 post 方法中的 b/w @ResponseStatus 和 ResponseEntity.created(location).build() 差异
- c# - 用户推送文件后如何重新加载头像并替换为默认图片?- ASP.NET MVC
- django - 如何在 django modelform 中执行查询?