Swift 3: How to create blurred side edges/corners

2019-02-05 03:05发布

Currently I have a CALayer applied to a UIImageView like so:

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

enter image description here

I'd like to achieve the following blurred effect as shown:

enter image description here

I've tried the following:

let blurEffect = UIBlurEffect(style: .light)

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

as well as:

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

visualEffectView.frame = staffImageView.bounds

imageView.addSubview(visualEffectView)

However, both do not achieve the results I want.

Can someone provide help on this? This seems rather simple, but I just cannot achieve it.

UPDATE: I've tried to play around with the gradient but not having much luck:

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)

Result:

enter image description here

2条回答
来,给爷笑一个
2楼-- · 2019-02-05 03:22

Base on Vincent Joy post,

Swift 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;
查看更多
干净又极端
3楼-- · 2019-02-05 03:40

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
查看更多
登录 后发表回答