如何使用Swift将模糊效果添加到UIImage中?

我想在UIimage中添加模糊效果,而不是UIImage View。 我可以在uiimage视图中添加模糊效果,如下所示:

let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = img.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] img.addSubview(blurEffectView) 

但是,我真的想加入uiimage。 因为我必须用文字画图像。 所以这是我的function:

 func textToImageWithPhoto(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(CGSize.init(width: 375, height: 375), false, scale) image.draw(in: CGRect(origin: CGPoint.init(x: 0, y: -100), size: CGSize(width: 375, height: 375*1.5))) let rect = CGRect(origin: CGPoint.init(x: 0, y: 187.5 - 150/2 ), size: CGSize.init(width: 375, height: 375)) text.draw(in: rect, withAttributes: textFontAttributes) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.saveData(img: newImage!, text: self.quotesTxt.text!) //SAVE CORE DATA return newImage! } 

有没有办法在绘制函数中添加模糊效果?

 extension UIIMageView { func addBlurEffect(){ //if !UIAccessibilityIsReduceTransparencyEnabled() { GlobalData.effectView.frame = self.bounds GlobalData.effectView.autoresizingMask = [.flexibleWidth , .flexibleHeight] self.addSubview(GlobalData.effectView) UIView.animate(withDuration: 0.3, animations: { GlobalData.effectView.effect = UIBlurEffect(style: .light) }) //} } func removeBlurEffect(){ for subView in self.subviews{ if subView is UIVisualEffectView{ UIView.animate(withDuration: 0.3, animations: { GlobalData.effectView.effect = nil }, completion: { (success:Bool) in subView.removeFromSuperview() }) } } } 

使用此扩展程序。 这对我有用。 我不尝试,但你可以改变扩展类型作为UIImage可能。