【问题标题】:Blur Effect using Swift language in iPhone在 iPhone 中使用 Swift 语言实现模糊效果
【发布时间】:2014-06-08 22:36:31
【问题描述】:

我一直在尝试使用 xcode 6(swift 语言)中的 UIImageView 来实现模糊效果,我正在尝试实现它以使 ImageView 下方的所有内容都变得模糊。

我无法让它工作,所以我请求堆栈溢出的你们帮助我。

如何做到这一点?

目前我写的代码是:


class blurImage: UIImageView {

    init(frame: CGRect) {
        super.init(frame: frame)

        var blur:UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        var effectView:UIVisualEffectView = UIVisualEffectView (effect: blur)

    }

}

【问题讨论】:

  • 你有工作的Objective C 代码吗?如果是这样,过渡的哪一部分正是导致问题的原因?如果不是,那么这可能是一个相当广泛的问题。
  • 我没有任何工作代码...我试图直接在 swift 中进行。
  • 然后我建议找到一个使用 Objective C 的解决方案,因为这个话题已经讨论过了,然后你尝试用 Swift 编写同样的东西。例如,您可以使用 UIInterpolatingMotionEffectUiView -addMotionEffect:(在 iOs7+ 上可用)。
  • 我会的!谢谢
  • @A-Live,据我所知 UIInterpolatingMotionEffect 不是模糊效果的目标。它是视差效果的目标

标签: ios iphone uiimageview swift


【解决方案1】:

您需要分配一个框架来实现模糊视图并将其添加为子视图

类模糊图像:UIImageView {

init(frame: CGRect) {
    super.init(frame: frame)

    var blur:UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
    var effectView:UIVisualEffectView = UIVisualEffectView (effect: blur)
    effectView.frame = frame
    addSubview(effectView)
}
 }

【讨论】:

  • 如何在 Storyboards 中使用这个类?
【解决方案2】:

我修改了 @Kuroros 类以使用 Storyboards

class BlurImage: UIImageView {

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    init(coder aDecoder: NSCoder!)
    {
        super.init(coder: aDecoder)

        let blur:UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        var effectView:UIVisualEffectView = UIVisualEffectView (effect: blur)
        effectView.frame = frame
        addSubview(effectView)
    }

}

【讨论】:

  • 我可能是错的,但模糊不应该是 let 而不是 var,因为它不会被修改?
【解决方案3】:

我修改了@fabian 的实现,因为如果使用自动布局,frame 的大小计算会出现问题。当您尝试读取init() 中的frame 数据时,它尚未正确计算并且对我来说具有大小(1000,1000),而应该是(420,420)。所以你需要稍后阅读和设置。我为此使用了layoutSubviews。设置frame = frame 也不起作用,因为它返回绝对容器位置,但我们需要盒子大小。

class BluredImage: UIImageView {

    var effectView:UIVisualEffectView!

    required init(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)!

        let blur:UIBlurEffect = UIBlurEffect(style: .light)
        effectView = UIVisualEffectView (effect: blur)

        addSubview(effectView)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        effectView.frame = bounds
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 2021-10-02
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多