【问题标题】:How to add blur effect into UIImage with Swift? [duplicate]如何使用 Swift 在 UIImage 中添加模糊效果? [复制]
【发布时间】:2017-02-22 08:04:35
【问题描述】:

我想在 UIimage 中添加模糊效果,而不是 UIImage 视图。 我可以在 uiimage 视图中添加模糊效果 就像这样:

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

但是,我真的很想添加到 uiimage 中。因为我必须用文字绘制图像。所以这是我的功能:

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

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

【问题讨论】:

  • 在图像上添加文本并返回新图像后,在blurredImage = UIImageEffects.imageByApplyingLightEffect(to: newImage)之前执行此操作
  • @Mukesh 谢谢!但是,当我添加模糊图像时,图像大小会改变!我想保持图像大小。我该如何解决?

标签: ios swift uiimageview uiimage uiblureffect


【解决方案1】:
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。

【讨论】:

  • OP已经提到他不想将blur effect添加到UIImageView
  • @DharmeshKheni 是的..没错:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 2015-07-13
  • 1970-01-01
相关资源
最近更新 更多