在框架的顶部和底部模糊 UiImageView

Blur UiImageView at top and bottom of the frame

我的视图控制器中有一个图像,而在图像视图的顶部我有一些标签,但由于标签文本可见性,我需要模糊 UIImageView 忽略器的顶部和底部以清楚地显示文本.

我附上了我的设计忽略器的屏幕截图,以获得清晰的想法。

正确输出请参考图片

将此代码添加到您的 UIImageView

let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: self.imgView.frame.size.width, height: self.imgView.frame.size.height*0.3))
gradientLayer.colors = [UIColor.black.withAlphaComponent(0.7).cgColor, UIColor.clear.cgColor]
self.imgView.layer.addSublayer(gradientLayer)

let gradientLayer2 = CAGradientLayer()
gradientLayer2.frame = CGRect(origin: CGPoint(x: 0, y: (self.imgView.frame.size.height-self.imgView.frame.size.height*0.3)), size: CGSize(width: self.imgView.frame.size.width, height: self.imgView.frame.size.height*0.3))
gradientLayer2.colors = [UIColor.clear.cgColor, UIColor.black.withAlphaComponent(0.7).cgColor]
self.imgView.layer.addSublayer(gradientLayer2)