如何使用Swift将模糊效果添加到UIImage中? [英] How to add blur effect into UIImage with Swift?

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

问题描述

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

I'd like to add blur effect in UIimage, not UIImage View. I can add blur effect into uiimage view just like this:

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

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

But, I really want to add into uiimage. Because I have to draw image with text. so here is my 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!
}

是否有某种方法可以在绘图功能中添加模糊效果?

And is there some way to add blur effect within draw function?

推荐答案

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.

Use this extension. it's work for me. I dont try but you can change extension type as UIImage maybe.

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

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