将渐变效果应用于模糊视图 [英] Apply gradient effect to a blur view

查看:39
本文介绍了将渐变效果应用于模糊视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Swift 中添加具有模糊效果的渐变视图?我可以很容易地向视图添加渐变层 (CAGradientLayer).我还可以单独添加一个模糊视图 (UIVisualEffectView).

How can I can add a gradient view that has blur effects in Swift? I can add a gradient layer (CAGradientLayer) quite easily to a view. I can also add a blur view (UIVisualEffectView) separately.

如何将两者结合起来创建一个也有渐变元素的模糊视图,其中完全模糊淡入淡出至无模糊?

How can I combine both to create a blur view that also has a gradient element where by full blur fading to no blur?

类似效果的示例:

推荐答案

要实现带有渐变模糊半径的模糊视图,可以执行以下操作(每个 Apple 文档):

To achieve a blur view with gradient blur radius, you can do the following (per Apple document):

let ciContext = CIContext(options: nil)

if let inputImage = CIImage(image: yourUIImage) {
        let extent = inputImage.extent
        let h = extent.size.height
        guard let gradient = CIFilter(name: "CILinearGradient") else { return }
        gradient.setValue(CIVector(x: 0, y: 0.85 * h), forKey: "inputPoint0")
        gradient.setValue(CIColor.green, forKey: "inputColor0")
        gradient.setValue(CIVector(x: 0, y: 0.50 * h), forKey: "inputPoint1")
        gradient.setValue(CIColor(red: 0, green: 1, blue: 0, alpha: 0), forKey: "inputColor1")

        guard let mask = CIFilter(name: "CIMaskedVariableBlur") else { return }
        mask.setValue(inputImage.clampedToExtent(), forKey: kCIInputImageKey)
        // Set your blur radius here, default is 5
        mask.setValue(10, forKey: kCIInputRadiusKey) 
        mask.setValue(gradient.outputImage, forKey: "inputMask")

        guard let output = mask.outputImage,
            let cgImage = ciContext.createCGImage(output, from: extent) else { return }
        outUIImage = UIImage(cgImage: cgImage)
}

这里,inputPoint0 是梯度斜坡的起点,inputPoint1 是终点.请注意,对于 CIVector y 从下到上增加.您设置的输入颜色无关紧要,只有它的 alpha 用于确定模糊半径.

Here, inputPoint0 is the starting point of gradient ramp, inputPoint1 is the ending point. Note that for CIVector y increases from bottom to top. The input color you set doesn't matter, only its alpha is used to determine blur radius.

对于将 CIFilter 动态应用于其下方图像的第二个问题,不,这是不可能的.backgroundFilters 上有一个 Apple 文档这可能会让您认为这是可行的,直到您看到底部...

For your second question of dynamically applying CIFilter to an image underneath it, no, it's not possible. There is an Apple document on backgroundFilters that might make you think it is doable, until you see at the bottom ...

iOS 中的图层不支持此属性.

This property is not supported on layers in iOS.

你应该做的是,每当你重置图像时,将上述操作应用于该图像并将其设置为图像视图.

What you should do is that, whenever you reset the image, apply the above operation to that image and set it to the image view.

这篇关于将渐变效果应用于模糊视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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