2017-02-22 74 views
0

我想在UIimage中添加模糊效果,而不是UIImage View。 我可以添加模糊效果到UIImage的觀點 就像這樣:如何使用Swift將模糊效果添加到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! 
} 

是否有某種方式來添加模糊效果內繪製函數?

+0

介紹瀏覽此處[模糊&着色圖像]((https://developer.apple.com/library/content/samplecode/UIImageEffects/Listings/UIImageEffects_UIImageEffects_h.html#//apple_ref/doc/uid/DTS40013396-UIImageEffects_UIImageEffects_h-DontLinkElementID_8 ) –

+0

在返回新圖像的同時在圖像上添加文本之後,在'blurredImage = UIImageEffects.imageByApplyingLightEffect(to:newImage)' –

+0

@Mukesh之前執行此操作,但是,當添加模糊圖像時,圖像大小會發生變化!保持圖像大小,我該如何解決它? –

回答

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也許。

+0

OP已經提到他不想在'UIImageView'中添加'模糊效果' –

+0

@DharmeshKheni yup..that是:( –

相關問題