基本上,我想创建一个使用 OPenGL 进行渲染的 ImageView。我最终的计划是将其用作带有 CIFilters 的视频播放器的基础。
我关注了一个 tutorial其中强调使用 OpenGL 技术来利用 GPU。本教程适用于 iOS。我将它映射到 Cocoa。
我不知道我在哪里失败了,但我得到的只是一个空白屏幕。
这是 View 。
import Cocoa
import OpenGL.GL3
class CoreImageView: NSOpenGLView {
var coreImageContext: CIContext?
var image: CIImage? {
didSet {
display()
}
}
override init?(frame frameRect: NSRect, pixelFormat format: NSOpenGLPixelFormat?) {
//Bad programming - Code duplication
let attrs: [NSOpenGLPixelFormatAttribute] = [
UInt32(NSOpenGLPFAAccelerated),
UInt32(NSOpenGLPFAColorSize), UInt32(32),
UInt32(NSOpenGLPFAOpenGLProfile),
UInt32( NSOpenGLProfileVersion3_2Core),
UInt32(0)
]
let pf = NSOpenGLPixelFormat(attributes: attrs)
super.init(frame: frameRect, pixelFormat: pf)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
//Bad programming - Code duplication
func defaultPixelFormat()->NSOpenGLPixelFormat?{
let attrs: [NSOpenGLPixelFormatAttribute] = [
UInt32(NSOpenGLPFAAccelerated),
UInt32(NSOpenGLPFAColorSize), UInt32(32),
UInt32(NSOpenGLPFAOpenGLProfile),
UInt32( NSOpenGLProfileVersion3_2Core),
UInt32(0)
]
return NSOpenGLPixelFormat(attributes: attrs)
}
func initialize(){
guard let pf = defaultPixelFormat() else {
Swift.print("pixelFormat could not be constructed")
return
}
self.pixelFormat = pf
guard let context = NSOpenGLContext(format: pf, share: nil) else {
Swift.print("context could not be constructed")
return
}
self.openGLContext = context
if let cglContext = context.cglContextObj {
coreImageContext = CIContext(cglContext: cglContext, pixelFormat: pixelFormat?.cglPixelFormatObj, colorSpace: nil, options: nil)
}else{
Swift.print("cglContext could not be constructed")
coreImageContext = CIContext(options: nil)
}
}
//--------------------------
override func draw(_ dirtyRect: NSRect) {
if let img = image {
let scale = self.window?.screen?.backingScaleFactor ?? 1.0
let destRect = bounds.applying(CGAffineTransform(scaleX: scale, y: scale))
coreImageContext?.draw(img, in: destRect, from: img.extent)
}
}
}
感谢任何帮助。完整的项目是here (XCode 8)和 here(Xcode 7)
最佳答案
我可能会建议查看 Simon 的 Core Image 助手——他在他的 github 上有这个东西,它基本上告诉核心图像使用 OpenGLES 2.0 上下文通过 GPU 渲染。当我试图弄清楚如何通过 GPU 进行渲染时,这对我很有帮助——不传输到 CPU 进行渲染是一个非常好的主意,因为传输需要很长时间(相对而言)。
关于swift - 如何使用 Swift 在 NSOpenGLView 中绘制图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39080469/