通过滑动在iOS上实现UIImage的实时模糊



如何在slidervaluechange(_:)上实现UIImage的实时模糊?

@IBOutlet weak var imageView: UIImageView!
@IBAction func sliderValueChanged(sender: UISlider) {
    let blurRadius = sender.value
    var img = imageView.image
    // some image processing for img
    //blurring for img
    // some another image processing for img
    imageView.image = img   
}

由于存在其他图像处理,我不适合UIImageView的模糊。

谢谢!

为了获得最佳性能,您应该使用GLKViewCIFilter而不是UIImageView

最简单的实现之一是这样的(Xcode6/Swift1.2):
import UIKit
import GLKit
class BlurImageView: GLKView {
    let clampFilter = CIFilter(name: "CIAffineClamp")!
    let blurFilter = CIFilter(name: "CIGaussianBlur")!
    let ciContext:CIContext
    override init(frame: CGRect) {
        let glContext = EAGLContext(API: .OpenGLES2)
        ciContext = CIContext(
            EAGLContext: glContext,
            options: [
                kCIContextWorkingColorSpace: NSNull()
            ]
        )
        super.init(frame: frame, context: glContext)
        enableSetNeedsDisplay = true
    }
    required init(coder aDecoder: NSCoder) {
        let glContext = EAGLContext(API: .OpenGLES2)
        ciContext = CIContext(
            EAGLContext: glContext,
            options: [
                kCIContextWorkingColorSpace: NSNull()
            ]
        )
        super.init(coder: aDecoder)
        context = glContext
        enableSetNeedsDisplay = true
    }
    @IBInspectable var inputImage: UIImage? {
        didSet {
            inputCIImage = inputImage.map { CIImage(image: $0)! }
        }
    }
    @IBInspectable var blurRadius: Float = 0 {
        didSet {
            blurFilter.setValue(blurRadius, forKey: "inputRadius")
            setNeedsDisplay()
        }
    }
    var inputCIImage: CIImage? {
        didSet { setNeedsDisplay() }
    }
    override func drawRect(rect: CGRect) {
        if let inputCIImage = inputCIImage {
            clampFilter.setValue(inputCIImage, forKey: kCIInputImageKey)
            blurFilter.setValue(clampFilter.outputImage!, forKey: kCIInputImageKey)
            let rect = CGRect(x: 0, y: 0, width: drawableWidth, height: drawableHeight)
            ciContext.drawImage(blurFilter.outputImage!, inRect: rect, fromRect: inputCIImage.extent())
        }
    }
}

然后,你可以这样使用:

class ViewController: UIViewController {
    @IBOutlet var imageView: BlurImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.inputImage = UIImage(named:"testImage")!
    }
    @IBAction func sliderValueChanged(sender: UISlider) {
        imageView.blurRadius = sender.value
    }
}

参见Core Image - objc简介。IO和它的示例代码以获得更多的解释和示例。

相关内容

  • 没有找到相关文章

最新更新