Artyom Vlasenko
Artyom Vlasenko

Reputation: 385

Render image in mtlView with Metal Api

help me figure out the metal api, I want to render the normal picture via mtlView, but it does not work for me, here's my code, what am I doing wrong? Next, I would like to use the UISlider and CIColorControls to change the contrast of this picture in 60fps, please explain.

import MetalKit

class ViewController: UIViewController, MTKViewDelegate {

    let device = MTLCreateSystemDefaultDevice()
    let colorSpace = CGColorSpaceCreateDeviceRGB()

    lazy var commandQueue: MTLCommandQueue = {
        [unowned self] in

        return self.device!.makeCommandQueue()
        }()!

    lazy var ciContext: CIContext = {
        [unowned self] in

        return CIContext(mtlDevice: self.device!)
        }()

    @IBOutlet weak var mtlView: MTKView!
    let filter = CIFilter(name: "CIPhotoEffectProcess" )
    let contrastFilter = CIFilter(name: "CIColorControls")
    var image = CIImage()

    @IBOutlet weak var slider: UISlider!


    override func viewDidLoad() {
        super.viewDidLoad()
        mtlView.delegate = self

        let img = UIImage(named: "picture")
        let ciImage = CIImage(image: img!)
        image = ciImage!
    }


    func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {

    }

    func draw(in view: MTKView) {
        guard let targetTexture = view.currentDrawable?.texture else {
            return
        }

        let commandBuffer = commandQueue.makeCommandBuffer()

        let bounds = CGRect(origin: CGPoint.zero, size: view.drawableSize)

        ciContext.render(image,
                         to: targetTexture,
                         commandBuffer: commandBuffer,
                         bounds: bounds,
                         colorSpace: colorSpace)

        commandBuffer?.present(view.currentDrawable!)
        commandBuffer?.commit()
    }
}

Upvotes: 2

Views: 1161

Answers (1)

Dannie P
Dannie P

Reputation: 4622

I don't see any code that would set device to the MTKView. An MTKView without a device would be returning empty drawable. I'd suggest adding this to the viewDidLoad:

mtlView.device = device

Upvotes: 0

Related Questions