【问题标题】:Adding multiple effects to a photo为照片添加多种效果
【发布时间】:2017-04-10 12:58:48
【问题描述】:

如何为图片添加多种效果?我有以下代码可以为照片添加效果:

func applyEffects(name: String, n: Float) {
    filter.setValue(self.cImage, forKeyPath: kCIInputImageKey)
    filter.setValue(n, forKeyPath: name)

    let result = filter.value(forKey: kCIOutputImageKey) as! CIImage
    let cgImage = CIContext.init(options: nil).createCGImage(result, from: result.extent)

    self.customImage = UIImage.init(cgImage: cgImage!)
}

func brightness(n: Float) {
    self.applyEffects(name: kCIInputBrightnessKey, n: n)
}

func contrast(n: Float) {
    self.applyEffects(name: kCIInputContrastKey, n: n)
}

func saturation(n: Float) {
    self.applyEffects(name: kCIInputSaturationKey, n: n)
}

但是当我想应用第二个效果时,第一个消失了。如何将两个或多个效果叠加在一起?

【问题讨论】:

    标签: ios swift uiimage cgimage


    【解决方案1】:

    我假设您使用 CIColorControls 作为过滤器。

    您需要将所有三个值传递到您的调用中:

    // The documentation doesn't give a default value for contrast, but for the others, I'm setting the defaults
    
    var brightness:Float = 1
    var contrast:Float = 1
    var saturation:Float = 1
    
    
    func applyEffects() {
    
        filter.setValue(self.cImage, forKeyPath: kCIInputImageKey)
        filter.setValue(brightness, forKeyPath: kCIInputBrightnessKey)
        filter.setValue(contrast, forKeyPath: kCIInputContrastKey)
        filter.setValue(saturation, forKeyPath: kCIInputSaturationKey)
    
        let result = filter.value(forKey: kCIOutputImageKey) as! CIImage
        let cgImage = CIContext.init(options: nil).createCGImage(result, from: result.extent)
    
        self.customImage = UIImage.init(cgImage: cgImage!)
    
    }
    
    func brightness(n: Float) {
        brightness = n
        applyEffects()
    }
    
    func contrast(n: Float) {
        contrast = n
        applyEffects()
    }
    
    func saturation(n: Float) {
        saturation = n
        applyEffects()
    }
    

    一个建议:

    如果您尝试通过 UISlider 使用“实时”更新,请使用 GLKView 并直接发送 CIImage。它使用GPU,并且设备上的性能大大提高。您始终可以创建 UIImage 用于保存、消息传递等。

    【讨论】:

    • 谢谢。我可以将 GLKView 与 UIViewController 一起使用吗?
    • 我愿意。 GLKViews 是 UIView 的子类。 objc.io/issues/21-camera-and-photos/core-image-intro CoreImage 这篇文章的顶部是一个使用它的 GitHub 的链接。大约一半(使用 OpenGL 提高性能)是关于如何使用它的一个很好的解释。
    猜你喜欢
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2023-03-28
    • 2012-02-12
    • 1970-01-01
    • 2014-01-22
    相关资源
    最近更新 更多