Search code examples
ioscore-imagecifilterglkview

How to implement a real-time performance view for core image filter


I would like to implement a real-time performance view for displaying core image filter output. Form the documentation of Apple, It seem that I should use a GPU based context for drawing.

There are some term I am confused. EAGLContext, CIContext, GLKView. What are these things? Also, should I use EAGLContext to create CGImage from CIImage and set it to UIImageView or using the GLKView. What are the difference of these two approaches?


Solution

  • You can keep your image on the GPU by avoiding UIImageView and using the OpenGL view, GLKView. To get that working with CoreImage, you need to create a CIContext with a EAGL context:

    let eaglContext = EAGLContext(API: .OpenGLES2)
    
    lazy var ciContext: CIContext =
    {
        [unowned self] in
    
        return CIContext(EAGLContext: self.eaglContext,
            options: [kCIContextWorkingColorSpace: NSNull()])
    }()
    

    The context of your GLKView should be the same eaglContext, it also needs a delegate that conforms to GLKViewDelegate.

    To display an image, invalidate the display with setNeedsDisplay(). This will call glkView(:drawInRect:) on the delegate and it's in here you use the Core Image context to draw the image to the GLKView:

        ciContext.drawImage(image,
            inRect: targetRect,
            fromRect: image.extent)
    

    Where image is the CIImage to display.

    If all that sounds like too much effort, I've done the work for you, check out my CoreImageHelpers repo.

    Simon