When I first started playing around with Core Image I struggled to find helpful documentation to render an image using OpenGL ES. This post demonstrates the easiest way to get up and running with a GLKView.
You can find the playground project here.
Render a CIImage using GLKView
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import GLKit import CoreImage import PlaygroundSupport class MyGLKView: GLKView { var image: CIImage? var ciContext: CIContext? override func draw(_ rect: CGRect) { if let image = self.image { // OpenGLES draws in pixels, not points so we scale to whatever the contents scale is. let scale = CGAffineTransform(scaleX: self.contentScaleFactor, y: self.contentScaleFactor) let drawingRect = rect.applying(scale) // The image.extent() is the bounds of the image. self.ciContext?.draw(image, in: drawingRect, from: image.extent) } } } // Create an image let imageURL = Bundle.main.url(forResource: "pulsar-logo", withExtension: "jpg")! let image = CIImage(contentsOf: imageURL) // Create a GLKView let eaglContext = EAGLContext(api: .openGLES2)! let view = MyGLKView(frame: CGRect(x: 0, y: 0, width: 128, height: 128), context: eaglContext) view.ciContext = CIContext(eaglContext: eaglContext) view.image = image // Tell the GLKView to draw view.setNeedsDisplay() // Tell playground to show PlaygroundPage.current.liveView = view |
The resulting output looks like this:
Nice work.
Hard coding the view coordinates makes it tough to view on different devices. Maybe use Class Sizes and Constraints instead? I have a UISlider that changes a CIImage in real time, but the CIImage origin x and y is the same as the GLKView, so the pic is in the bottom left corner. I would rather center it, or have the view size to fit. Anyway, thanks for taking the time to post this….not a lot of info out there. Maybe Apple should update FunHouse. ;o)
Also, a GLKView is designed for animation. Just use UIImageView to display an image. My UISlider adjusts a CIFilter in realtime in my GLKView. Again, they are designed for animation….NOT displaying images.