MTKView显示CIImage

import UIKit
import Metal
import MetalKit

class CIImageView: MTKView{
    private var ciContext: CIContext?
    var image: CIImage?{
        didSet{
            setNeedsDisplay()
        }
    }
    
    override init(frame frameRect: CGRect, device: MTLDevice?) {
        super.init(frame: frameRect, device: device)
        ciContext = CIContext(mtlDevice: self.device!, options: [CIContextOption.workingColorSpace: NSNull()])
        self.isPaused = true
        self.enableSetNeedsDisplay = true
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        guard let image = image else { return }
        guard let commandBuffer = self.device?.makeCommandQueue()?.makeCommandBuffer() else { return }
        guard let drawingTexture = self.currentDrawable?.texture else { return }
        guard let currentDrawable = self.currentDrawable else { return }
        
        self.drawableSize = image.extent.size
        ciContext?.render(image, to: drawingTexture, commandBuffer: commandBuffer, bounds: CGRect(x: 0, y: 0, width: image.extent.width, height: image.extent.height), colorSpace: CGColorSpaceCreateDeviceRGB())
        commandBuffer.present(currentDrawable)
        commandBuffer.commit()
        MYLog(message: self.frame)
        MYLog(message: self.drawableSize)
    }
}

你可能感兴趣的:(MTKView显示CIImage)