Swift 3:如何创建UIImageView模糊的侧边/角?

时间:2016-12-12 02:11:28

标签: ios swift uiimageview swift3 calayer

目前,CALayer已应用于UIImageView,如此:

let l: CALayer = imageView.layer
l.masksToBounds = true
l.cornerRadius = 20.0

enter image description here

我希望达到如下所示的模糊效果:

enter image description here

我尝试过以下方法:

let blurEffect = UIBlurEffect(style: .light)

let visualEffectView = UIVisualEffectView(effect: blurEffect)
imageView.addSubview(visualEffectView)

以及:

var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))

visualEffectView.frame = staffImageView.bounds

imageView.addSubview(visualEffectView)

但是,两者都没有达到我想要的效果。

有人可以提供帮助吗?这似乎相当简单,但我无法实现它。

更新 我试过玩渐变但没有太多运气:

var maskLayer = CAGradientLayer()
maskLayer.frame = cell.imageView.bounds
let black = UIColor.white.cgColor
let clear = UIColor(white: 1, alpha: 0).cgColor
maskLayer.colors = [black, clear]
maskLayer.locations = [0.0, 0.10]
maskLayer.startPoint = CGPoint(x: 1, y: 0)
maskLayer.endPoint = CGPoint(x: 1, y: 1)
cell.imageView.layer.addSublayer(maskLayer)

结果:

enter image description here

2 个答案:

答案 0 :(得分:12)

Swift 4

let maskLayer = CAGradientLayer()
maskLayer.frame = yourImageView.bounds
maskLayer.shadowRadius = 5
maskLayer.shadowPath = CGPath(roundedRect: YourImagView.bounds.insetBy(dx: 5, dy: 5), cornerWidth: 10, cornerHeight: 10, transform: nil)
maskLayer.shadowOpacity = 1
maskLayer.shadowOffset = CGSize.zero
maskLayer.shadowColor = UIColor.white.cgColor        
yourImageView.layer.mask = maskLayer

答案 1 :(得分:4)

基于Vincent Joy的帖子,

斯威夫特3:

let maskLayer = CAGradientLayer()
maskLayer.frame = yourImageView.bounds
maskLayer.shadowRadius = 5
maskLayer.shadowPath = CGPathCreateWithRoundedRect(CGRectInset(yourImageView.bounds, 5, 5), 10, 10, nil)
maskLayer.shadowOpacity = 1;
maskLayer.shadowOffset = CGSizeZero;
maskLayer.shadowColor = UIColor.whiteColor().CGColor        
yourImageView.layer.mask = maskLayer;

Swift 4:

let maskLayer = CAGradientLayer()
maskLayer.frame = YourImagView.bounds
maskLayer.shadowRadius = 5
maskLayer.shadowPath = CGPath(roundedRect: YourImagView.bounds.insetBy(dx: 5, dy: 5), cornerWidth: 10, cornerHeight: 10, transform: nil)
maskLayer.shadowOpacity = 1;
maskLayer.shadowOffset = CGSize.zero;
maskLayer.shadowColor = UIColor.white.cgColor
YourImagView.layer.mask = maskLayer;