渲染一个MTIImage

时间:2018-06-25 14:00:26

标签: ios swift metal

请不要以为我只是在学习Swift。

最近我安装了MetalPetal框架,并按照说明进行操作:

  

https://github.com/MetalPetal/MetalPetal#example-code

但是由于MTIContext,我得到了错误。也许我必须声明更多MetalPetal吗?

我的代码:

My Code

import UIKit
import MetalPetal
import CoreGraphics

class ViewController: UIViewController {

    @IBOutlet weak var image1: UIImageView!
    override func viewDidLoad() {

        super.viewDidLoad()




        weak var image: UIImage?
        image = image1.image
        var ciImage = CIImage(image: image!)
        var cgImage1 = convertCIImageToCGImage(inputImage: ciImage!)
        let imageFromCGImage = MTIImage(cgImage: cgImage1!)


        let inputImage = imageFromCGImage
        let filter = MTISaturationFilter()
        filter.saturation = 1
        filter.inputImage = inputImage

        let outputImage = filter.outputImage


        let context = MTIContext()

        do {
            try context.render(outputImage, to: pixelBuffer)

            var image3: CIImage? = try context.makeCIImage(from: outputImage!)

            //context.makeCIImage(from: image)

            //context.makeCGImage(from: image)
        } catch {
            print(error)
        }





        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func convertCIImageToCGImage(inputImage: CIImage) -> CGImage? {
        let context = CIContext(options: nil)
        if let cgImage = context.createCGImage(inputImage, from: inputImage.extent) {
            return cgImage
        }
        return nil
    }

}

@YuAo

1 个答案:

答案 0 :(得分:3)

输入图片

UIImage基于基础Quartz图像(可以使用cgImage检索)或基础Core图像(可以从具有ciImage的UIImage检索)。

MTIImage提供两种类型的构造函数。

MTIContext

必须使用可以通过调用MTLCreateSystemDefaultDevice()进行检索的设备来初始化MTIContext。

渲染

不需要渲染到像素缓冲区。我们可以通过调用makeCGImage获得结果。

测试

我已将您的源代码带到上面,并略微调整了以适应上述要点。

我还添加了第二个UIImageView来查看过滤的结果。我也将饱和度更改为0,以查看过滤器是否有效

如果涉及GPU或着色器,则有必要在真实设备上而不是在模拟器上进行测试。

结果如下:

saturation test

在上方区域中看到原始jpg,在下方区域中应用滤镜。

快速

产生此结果的简化Swift代码如下:

override func viewDidLoad() {

    super.viewDidLoad()

    guard let image = UIImage(named: "regensburg.jpg") else { return }
    guard let cgImage = image.cgImage else { return }

    imageView1.image = image

    let filter = MTISaturationFilter()
    filter.saturation = 0
    filter.inputImage = MTIImage(cgImage: cgImage)

    if let device = MTLCreateSystemDefaultDevice(),
        let outputImage = filter.outputImage {
        do {
            let context = try MTIContext(device: device)
            let filteredImage = try context.makeCGImage(from: outputImage)
            imageView2.image = UIImage(cgImage: filteredImage)
        } catch {
            print(error)
        }
    }
}