[英]Real-time blur for UIImage by sliding on iOS
How to achieve the real time blurring for UIImage on sliderValueChanged(_:)? 如何在liderValueChanged(_ :)上实现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
}
I don't fit the blurring for UIImageView due to the presence of other image processing. 由于存在其他图像处理,我不适合UIImageView的模糊处理。
Thanks! 谢谢!
For maximum performance, you should use GLKView
with CIFilter
instead of UIImageView
. 为了获得最佳性能,应该将
GLKView
与CIFilter
一起使用,而不是UIImageView
。
One of the simplest implementation would be something like this (Xcode6/Swift1.2): 最简单的实现之一就是这样的代码(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. 有关更多说明和示例,请参见“ Core Image简介-objc.io”及其示例代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.