iOS 小知识-添加shadow(阴影)

普通添加

        let layer = view.layer
        layer.shadowColor = UIColor.black.cgColor//阴影颜色
        layer.shadowOffset = CGSize(width: 10, height: 10)//width表示阴影与x的便宜量,height表示阴影与y值的偏移量
        layer.shadowOpacity = 0.4//阴影透明度,默认为0则看不到阴影
        layer.shadowRadius = 5;

解释:

1.shadowColor:阴影颜色,可设置透明度等.
2.shadowOffset:偏移量.,xy表示view左上角,width表示阴影与x的偏移量,height表示阴影与y值的偏移量
3.shadowOpacity = 0.4//阴影透明度,默认为0则看不到阴影.因此要看到阴影这个值必须大于0,shadowColor的透明度也要大于0
4.shadowRadius:5.模糊计算的半径,取平均值的半径,设置为0的话则为一个矩形块.
5.模糊度的解释:每一个像素取平均值,分母的取值范围,越大越模糊.感觉这篇文章讲的比较容易懂
(http://www.dongcoder.com/detail-22914.html).
6.注意:如果clipsToBounds设置为YES,则阴影效果消失

自定义添加

自定义阴影形状和位置则需要使用path.把view想象成一块画布,在上面绘制阴影位置和区域,一般会超出这块画布

   func  addPathShadow(view:UIView) {
        //用路径定义shadow位置和形状
        let size = view.bounds.size
        let width = size.width
        let height = size.height
        let depth = CGFloat(11.0)
        let lessDepth = 0.8 * depth
        let curvyness = CGFloat(5)
        let radius = CGFloat(1)

        let path = UIBezierPath()

        // top left
        path.move(to: CGPoint(x: radius, y: height))

        // top right
        path.addLine(to: CGPoint(x:width - 2 * radius,y:height))

        // bottom right + a little extra
        path.addLine(to: CGPoint(x: width - 2*radius, y: height + depth))

        // path to bottom left via curve
        path.addCurve(to: CGPoint(x: radius, y: height + depth), controlPoint1: CGPoint(x: width - curvyness, y: height + lessDepth - curvyness), controlPoint2: CGPoint(x: curvyness, y: height + lessDepth - curvyness))


        let layer = view.layer
        layer.shadowPath = path.cgPath
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.3
        layer.shadowRadius = radius
        layer.shadowOffset = CGSize(width: 0, height: -3)
    }

参考资料

四个demo

你可能感兴趣的:(iOS 小知识-添加shadow(阴影))