iOS中圆角实现非常容易,对比而言,设置阴影则需要设置颜色,偏移位置,阴影透明度,阴影半径:
<pre><code>` /* The color of the shadow. Defaults to opaque black. Colors created
* from patterns are currently NOT supported. Animatable. */
/** Shadow properties. **/
open var shadowColor: CGColor?
/* The opacity of the shadow. Defaults to 0. Specifying a value outside the
* [0,1] range will give undefined results. Animatable. */
open var shadowOpacity: Float
/* The shadow offset. Defaults to (0, -3). Animatable. */
open var shadowOffset: CGSize
/* The blur radius used to create the shadow. Defaults to 3. Animatable. */
open var shadowRadius: CGFloat`</code></pre>
图一实现的代码非常原始,简单设置了阴影颜色:
<pre><code>` let view:UIView = UIView.init(frame: CGRect(x: 50, y: 200, width: 50, height: 50))
view.backgroundColor = UIColor.blue
view.layer.shadowColor = UIColor.red.cgColor
view.layer.shadowOpacity = 1.0
self.view.addSubview(view)`</code></pre>
对比图一阴影分步的更加均匀,shadowOffset都设置了0:
<pre><code>` let view1:UIView = UIView.init(frame: CGRect(x: 150, y: 200, width: 50, height: 50))
view1.backgroundColor = UIColor.blue
view1.layer.shadowColor = UIColor.red.cgColor
view1.layer.shadowOpacity = 1.0
view1.layer.shadowOffset = CGSize(width: 0, height: 0)
view1.layer.shadowRadius = 4
self.view.addSubview(view1)`</code></pre>
图三是设置阴影,同时设置圆角,阴影不显示:
<pre><code>` let view2:UIView = UIView.init(frame: CGRect(x: 250, y: 200, width: 50, height: 50))
view2.backgroundColor = UIColor.blue
view2.layer.masksToBounds = true
view2.layer.cornerRadius = 25
view2.layer.shadowColor = UIColor.red.cgColor
view2.layer.shadowOpacity = 1.0
view2.layer.shadowOffset = CGSize(width: 0, height: 0)
view2.layer.shadowRadius = 4
self.view.addSubview(view2)`</code></pre>
图四既设置圆角同时设置阴影:
<pre><code>` let view2:UIView = UIView.init(frame: CGRect(x: 260, y: 200, width: 50, height: 50))
view2.backgroundColor = UIColor.blue
view2.layer.cornerRadius = 25
view2.layer.shadowColor = UIColor.red.cgColor
view2.layer.shadowOpacity = 1.0
view2.layer.shadowOffset = CGSize(width: 0, height: 0)
view2.layer.shadowRadius = 4
view2.layer.masksToBounds = false
self.view.addSubview(view2)`</code></pre>
<pre><code>` let shadowView:UIView = UIView(frame: CGRect(x: 50, y: 300, width: 50, height: 50))
shadowView.backgroundColor = UIColor.white
shadowView.layer.shadowColor = UIColor.red.cgColor
shadowView.layer.shadowOpacity = 1.0
shadowView.layer.shadowOffset = CGSize(width: 0, height: 0)
shadowView.layer.shadowRadius = 4
shadowView.clipsToBounds = false
shadowView.layer.cornerRadius = 25.0
let innerView:UIView = UIView.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
innerView.backgroundColor = UIColor.yellow
innerView.clipsToBounds = true
innerView.layer.cornerRadius = 25
shadowView.addSubview(innerView)
self.view.addSubview(shadowView)`</code></pre>