如何使用Swift模糊UIImageView中的现有图像?

时间:2016-12-15 04:39:46

标签: ios swift uiimageview cifilter ciimage

设置很简单。

  • 带有UIImageView的ViewController,已分配图像。
  • UIButton,点击时会模糊UIImageView中的图像。

Storyboard

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var bg: UIImageView!

    @IBAction func blur(_ sender: Any) {
        let inputImage = CIImage(cgImage: (bg.image?.cgImage)!)

        let filter = CIFilter(name: "CIGaussianBlur")
        filter?.setValue(inputImage, forKey: "inputImage")
        filter?.setValue(10, forKey: "inputRadius")
        let blurred = filter?.outputImage
        bg.image = UIImage(ciImage: blurred!)
    }
}

单击该按钮时,屏幕变为白色。无法弄清楚我做错了什么。谁知道我做错了什么?

11 个答案:

答案 0 :(得分:20)

您只需使用UIVisualEffect即可实现模糊效果。当您尝试使用CoreImage实现模糊效果时,请在import CoreImage之后的代码中尝试下面的代码。

var context = CIContext(options: nil)

func blurEffect() {

    let currentFilter = CIFilter(name: "CIGaussianBlur") 
    let beginImage = CIImage(image: bg.image!)
    currentFilter!.setValue(beginImage, forKey: kCIInputImageKey)
    currentFilter!.setValue(10, forKey: kCIInputRadiusKey)

    let cropFilter = CIFilter(name: "CICrop")
    cropFilter!.setValue(currentFilter!.outputImage, forKey: kCIInputImageKey)
    cropFilter!.setValue(CIVector(cgRect: beginImage!.extent), forKey: "inputRectangle")

    let output = cropFilter!.outputImage 
    let cgimg = context.createCGImage(output!, from: output!.extent)
    let processedImage = UIImage(cgImage: cgimg!)
    bg.image = processedImage
}

输出:

enter image description here

注意:我建议您在真实设备中测试代码,因为CoreImage上的模拟器性能太慢。

答案 1 :(得分:13)

对于那些❤️协议

protocol Bluring {
    func addBlur(_ alpha: CGFloat)
}

extension Bluring where Self: UIView {
    func addBlur(_ alpha: CGFloat = 0.5) {
        // create effect
        let effect = UIBlurEffect(style: .dark)
        let effectView = UIVisualEffectView(effect: effect)

        // set boundry and alpha
        effectView.frame = self.bounds
        effectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        effectView.alpha = alpha

        self.addSubview(effectView)
    }
}

// Conformance
extension UIView: Bluring {}

// use
someImageview.addBlur()

答案 2 :(得分:4)

以下是我在SWIFT 3.1中获得预期结果的方法: 希望它会有所帮助。

func blurImage(image:UIImage) -> UIImage? {
        let context = CIContext(options: nil)
        let inputImage = CIImage(image: image)
        let originalOrientation = image.imageOrientation
        let originalScale = image.scale

        let filter = CIFilter(name: "CIGaussianBlur")
        filter?.setValue(inputImage, forKey: kCIInputImageKey)
        filter?.setValue(10.0, forKey: kCIInputRadiusKey) 
        let outputImage = filter?.outputImage

        var cgImage:CGImage?

        if let asd = outputImage
        {
            cgImage = context.createCGImage(asd, from: (inputImage?.extent)!)
        }

        if let cgImageA = cgImage
        {
            return UIImage(cgImage: cgImageA, scale: originalScale, orientation: originalOrientation)
        }

        return nil
    }

答案 3 :(得分:1)

CoreImage实际上有一个便捷的实现方式 https://developer.apple.com/documentation/coreimage/ciimage/1645897-applyinggaussianblur

extension UIImage {

func blur(_ radius: Double) -> UIImage? {
    if let img = CIImage(image: self) {
        return UIImage(ciImage: img.applyingGaussianBlur(sigma: radius))
    }
    return nil
}

答案 4 :(得分:0)

我在NSObject类中创建了模糊,因此我可以轻松地在整个项目中使用此方法。

import UIKit

class ViewController: UIViewController
{
   var blurEffectView : UIVisualEffectView!
    override func viewDidLoad() {
        super.viewDidLoad()

      blurEffectView = Helper.addBlurView((imgView)!)
      self.imgView.addSubview(blurEffectView)
}

在ViewController中,我创建了 UIVisualEffectView 的对象。然后调用辅助类方法来添加模糊。

if (/* your condition */) {
    $user = User::where('email', $credentials['email'])->first();
    Auth::login($user);
    return $this->handleUserWasAuthenticated($request, $throttles);
}

答案 5 :(得分:0)

使用此:

 import UIKit

    class ViewController: UIViewController {

        @IBOutlet weak var bgImageView: UIImageView!
        @IBOutlet weak var blurButton: UIButton!


        override func viewDidLoad() {
            super.viewDidLoad()
            // 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.
        }


        @IBAction func blurButtonTapped(_ sender: Any) {

                let inputImage = CIImage(cgImage: (self.bgImageView.image?.cgImage)!)
                let filter = CIFilter(name: "CIGaussianBlur")
                filter?.setValue(inputImage, forKey: "inputImage")
                filter?.setValue(10, forKey: "inputRadius")
                let blurred = filter?.outputImage

                var newImageSize: CGRect = (blurred?.extent)!
                newImageSize.origin.x += (newImageSize.size.width - (self.bgImageView.image?.size.width)!) / 2
                newImageSize.origin.y += (newImageSize.size.height - (self.bgImageView.image?.size.height)!) / 2
                newImageSize.size = (self.bgImageView.image?.size)!

                let resultImage: CIImage = filter?.value(forKey: "outputImage") as! CIImage
                let context: CIContext = CIContext.init(options: nil)
                let cgimg: CGImage = context.createCGImage(resultImage, from: newImageSize)!
                let blurredImage: UIImage = UIImage.init(cgImage: cgimg)
                self.bgImageView.image = blurredImage
        }

    }

输出:

enter image description here

Gitbub链接:

https://github.com/k-sathireddy/ImageBlurEffect

答案 6 :(得分:0)

使用UIVisualEffectViewCIFilter的解决方案会有糟糕的表现或糟糕的结果(在 Joes 答案中可以看到图像周围产生模糊的明亮边框)或两者兼而有之。 / p>

性能最佳的解决方案之一是StackBlur,它使用了一种能够有效逼近模糊的聪明算法:

  

这是高斯模糊和Box模糊之间的折衷   比Box Blur看起来更漂亮,但是比我的快7倍   高斯模糊实现。我称之为Stack Blur因为这个   最好地描述了这个过滤器在内部如何工作:它创建了一种   移动堆栈(或者可能是一个"河内塔"种类的结构)的颜色   同时扫描图像。这座"塔"控制权重   在卷积核中的单个像素并给出像素   在中心最重的。速度的秘诀在于   算法只需要在堆栈的右侧添加一个新像素   并同时删除最左边的像素。剩下的颜色   在堆栈的最顶层上添加或减少   一,取决于他们是在右侧还是左侧   叠加。

查看StackBlur on Github

有很多版本,还有Swift端口,但这些版本比Obj-C版本慢得多。

答案 7 :(得分:0)

检查是否有零。我遇到了类似的问题,但就我而言,我没有创建CIImage的新实例,因为该image.ciimage即将失效。

答案 8 :(得分:0)

我的扩展名

extension UIImage {
    
    func blurImage(radius: CGFloat = 10) -> UIImage? {
        guard let cgImage = cgImage else { return nil }
        let inputCIImage = CIImage(cgImage: cgImage)
        let context = CIContext(options: nil)
        
        let filter = CIFilter(name: "CIGaussianBlur")
        filter?.setValue(inputImage, forKey: kCIInputImageKey)
        filter?.setValue(radius, forKey: kCIInputRadiusKey)
        let outputImage = filter?.outputImage
        
        if let outputImage = outputImage,
            let cgImage = context.createCGImage(outputImage, from: inputImage.extent) {
            
            return UIImage(
                cgImage: cgImage,
                scale: scale,
                orientation: imageOrientation
            )
        }
        return nil
    }
 }

答案 9 :(得分:-1)

您可以按UIBlurEffectUIVisualEffectView添加模糊效果:

@IBAction func blur(_ sender: Any) {

    let darkBlur = UIBlurEffect(style: UIBlurEffectStyle.dark) 
    let blurView = UIVisualEffectView(effect: darkBlur)
    blurView.frame = bg_imagview.bounds
    blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    bg_imagview.addSubview(blurView)

}

答案 10 :(得分:-2)

嘿,像我一样的所有LAZY家伙。

只需添加带有cocoapods的SwifterSwift。

导入SwifterSwift。

import SwifterSwift

像下面一样模糊图像视图。

someImageView.blur()