How to achieve the real time blurring for UIImage on sliderValueChanged(_:)?
@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
}
I don't fit the blurring for UIImageView due to the presence of other image processing.
Thanks!
For maximum performance, you should use GLKView
with CIFilter
instead of UIImageView
.
One of the simplest implementation would be something like this (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())
}
}
}
Then, you can use this like:
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
}
}
See An Introduction to Core Image - objc.io and it's sample code for more explanations and examples.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.