内容字号:默认大号超大号

段落设置:段首缩进取消段首缩进

字体设置:切换到微软雅黑切换到宋体

圆角和阴影并存的三种方式

2018-12-04 21:44 出处:清屏网 人气: 评论(0

因为最普通的设置圆角的方法中,layer.masksToBounds = true会将阴影也会裁剪到,导致阴影设置失效,所以可以通过以下三种方法来让圆角和阴影并存:

1.通过添加一个阴影View放在目标View下面

```

func byAddingAnotherView() {

let shadowView = UIView.init()

shadowView.layer.shadowColor = UIColor.darkGray.cgColor

shadowView.layer.shadowOffset = CGSize(width: 0.0, height: 10)

shadowView.layer.shadowOpacity = 1

shadowView.layer.shadowRadius = 15

shadowView.layer.cornerRadius = 25

shadowView.frame = CGRect.init(x: (UIScreen.main.bounds.size.width - 50)/2, y: 100, width: 50, height: 50)

view.addSubview(shadowView)

let button = UIButton.init(type: .custom)

button.frame = shadowView.bounds

button.backgroundColor = UIColor.blue

button.layer.cornerRadius = 25

button.layer.masksToBounds = true

shadowView.addSubview(button)

}

```

2.通过添加一个阴影layer放在目标View的layer下面

```

func byAddingAnotherLayer() {

let button = UIButton.init(type: .custom)

button.frame = CGRect.init(x: (UIScreen.main.bounds.size.width - 50)/2, y: 200, width: 50, height: 50)

button.backgroundColor = UIColor.blue

button.layer.cornerRadius = 25

button.layer.masksToBounds = true

view.addSubview(button)

let subLayer = CALayer.init()

subLayer.frame = button.frame

subLayer.cornerRadius=25

subLayer.backgroundColor = UIColor.blue.cgColor

subLayer.masksToBounds=false

subLayer.shadowColor = UIColor.darkGray.cgColor

subLayer.shadowOffset = CGSize(width: 0.0, height: 10)

subLayer.shadowOpacity = 1;

subLayer.shadowRadius = 15;

view.layer.insertSublayer(subLayer, below: button.layer)

}

```

3.通过设置目标view的layer.shadowPath属性来设置阴影

```

func byChangeLayer() {

let button = UIButton.init(type: .custom)

button.frame = CGRect.init(x: (UIScreen.main.bounds.size.width - 50)/2, y: 300, width: 50, height: 50)

button.backgroundColor = UIColor.blue

view.addSubview(button)

button.layer.cornerRadius = 25

button.layer.masksToBounds = false

button.layer.shadowColor = UIColor.darkGray.cgColor

button.layer.shadowOffset = CGSize(width: 0.0, height: 10)

button.layer.shadowOpacity = 1

button.layer.shadowRadius = 15

button.layer.shadowPath = UIBezierPath.init(roundedRect: button.layer.bounds, cornerRadius: button.layer.cornerRadius).cgPath

button.layer.shouldRasterize = true

button.layer.rasterizationScale = UIScreen.main.scale

}

```

第一种方式的缺点主要是需要新创建一个View,造成额外的性能开销

第二种方式需要获取到view的superView,将阴影layer添加到superView的layer中去,有一定的局限性

第三种方式性能较好,因为使用shadowPath可以有效避免了offscreen渲染,因为仅需要直接绘制路径即可,不需要提前读取图像去渲染。

效果图:

![](https://user-gold-cdn.xitu.io/2018/12/4/167773a6aa453932?w=380&h=739&f=png&s=36864)

代码在此:

https://github.com/577528249/SwiftDemo/tree/master/CornerAndShadow

分享给小伙伴们:
本文标签: iOS开发

相关文章

发表评论愿您的每句评论,都能给大家的生活添色彩,带来共鸣,带来思索,带来快乐。

CopyRight © 2015-2016 QingPingShan.com , All Rights Reserved.

清屏网 版权所有 豫ICP备15026204号