自定义 BlurEffect

Mar 25, 2020 • 预计阅读时间 1 分钟

系统提供的 UIBlurEffect 毛玻璃效果不能调整参数,只能选择内置的几个效果。

要实现自定义的毛玻璃效果,需要使用私有类 _UICustomBlurEffect,虽然没有文档但是大牛们已经研究出来使用方法了,我做了一点微小的封装提高便利性。

import UIKit

typealias CustomBlurEffectKey = String

private let colorTintKey: CustomBlurEffectKey = "colorTint"
private let colorTintAlphaKey: CustomBlurEffectKey = "colorTintAlpha"
private let blurRadiusKey: CustomBlurEffectKey = "blurRadius"
private let blurScaleKey: CustomBlurEffectKey = "scale"

@objc public class CustomBlurEffectView: UIVisualEffectView {

    @objc public var colorTint: UIColor? {
        get {
            return blurValue(forKey: colorTintKey) as? UIColor
        }

        set {
            setBlurValue(newValue, forKey: colorTintKey)
        }
    }

    @objc public var colorTintAlpha: CGFloat {
        get {
            return blurValue(forKey: colorTintAlphaKey) as? CGFloat ?? 0
        }

        set {
            setBlurValue(newValue, forKey: colorTintAlphaKey)
        }
    }

    @objc public var blurRadius: CGFloat {
        get {
            return blurValue(forKey: blurRadiusKey) as? CGFloat ?? 0
        }

        set {
            setBlurValue(newValue, forKey: blurRadiusKey)
        }
    }

    @objc public var blurScale: CGFloat {
        get {
            return blurValue(forKey: blurScaleKey) as? CGFloat ?? 0
        }

        set {
            setBlurValue(newValue, forKey: blurScaleKey)
        }
    }

    private var customBlurEffect: UIBlurEffect?

    @objc public convenience init() {
        let customBlurEffect = (NSClassFromString("_UICustomBlurEffect") as! UIBlurEffect.Type).init()
        self.init(effect: customBlurEffect)

        self.customBlurEffect = customBlurEffect
        blurScale = 1
    }

    private func blurValue(forKey key: String) -> Any? {
        return customBlurEffect?.value(forKey: key)
    }

    private func setBlurValue(_ value: Any?, forKey key: String) {
        customBlurEffect?.setValue(value, forKey: key)
        effect = customBlurEffect
    }
}
iOS

搜索项目里的私有 API

comments powered by Disqus