相关疑难解决方法(0)

为什么 UIGraphicsGetCurrentContext 在 UIGraphicsBeginImageContext 之后返回 nil

我正在按照代码示例制作模糊的 UILabel,/sf/answers/4355743591/

我的要求是在标签初始化后使标签模糊,而不是blur在运行时调用该方法。但是,当我尝试blur在标签初始化后调用时,返回的值UIGraphicsGetCurrentContext因此nil出现“致命错误:在展开可选值时意外发现 nil”

UIGraphicsBeginImageContext(bounds.size)
print("DEBUG: bounds.size", bounds.size)
self.layer.render(in: UIGraphicsGetCurrentContext()!) // <- return nil
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print("DEBUG: image image", image)
Run Code Online (Sandbox Code Playgroud)

我尝试在以下所有位置单独添加代码,现在可以获取上下文,但它不会按预期生成模糊效果。

override func layoutSubviews() {
    super.layoutSubviews()
    self.blur()
}

// OR
    
override func draw(_ rect: CGRect) {
    super.draw(rect)
    self.blur()
}
Run Code Online (Sandbox Code Playgroud)

完整的代码片段,

class BlurredLabel: UILabel {

    func blur(_ blurRadius: Double = 2.5) {        
        let blurredImage = getBlurryImage(blurRadius)
        let blurredImageView = UIImageView(image: blurredImage)
        blurredImageView.translatesAutoresizingMaskIntoConstraints = false
        blurredImageView.tag = 100
        blurredImageView.contentMode …
Run Code Online (Sandbox Code Playgroud)

core-image uikit ios swift

4
推荐指数
1
解决办法
1365
查看次数

标签 统计

core-image ×1

ios ×1

swift ×1

uikit ×1