如何使用 Swift 模糊 UIImageView 中的现有图像? [英] How to blur an existing image in a UIImageView with Swift?

查看:19
本文介绍了如何使用 Swift 模糊 UIImageView 中的现有图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置很简单.

  • 一个带有 UIImageView 的 ViewController 并分配了一个图像.
  • 一个 UIButton,点击后会模糊 UIImageView 中的图像.

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!)
    }
}

单击按钮时,屏幕会变成白色.无法弄清楚我做错了什么.有谁知道我做错了什么?

When the button is clicked the screen just turns white. Can't figure out what I'm doing wrong. Anyone know what I'm doing wrong?

推荐答案

你可以简单地使用UIVisualEffect来实现模糊效果.当您尝试使用 CoreImage 实现模糊效果时.在 import CoreImage 到您的类之后尝试下面的代码.

You could simply use UIVisualEffect to achieve blur effect. As you trying to achieve a blur effect using CoreImage.Try below code after import CoreImage to your class.

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
}

输出:

注意:建议您在真机上测试代码,因为模拟器在 coreImage 上的性能太慢了.

Note: I recommend you to test the code in real device as Simulator performance is too slow on coreImage.

这篇关于如何使用 Swift 模糊 UIImageView 中的现有图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆