为UIView设置阴影效果
阴影效果的实现,苹果提供了很好的实现方式,主要是layer层的绘制,具体的原理,可以查询资料.
注意一定不要写,否则不会显示阴影
self.view.layer.masksToBounds = YES;
或者
self.view.layer.clipsToBounds = YES;
1.最直接,也是比较简单的方式:效果如红色view
func addShadowView(){
let shadowView = UIView(frame: CGRectMake(100, 100, 100, 100))
shadowView.backgroundColor = UIColor.redColor()
//setShadow
shadowView.layer.cornerRadius = 5;
shadowView.layer.shadowColor = UIColor.blackColor().CGColor
shadowView.layer.shadowOffset = CGSizeMake(5, 10)
shadowView.layer.shadowOpacity = 1.0
shadowView.layer.shadowRadius = 5;
//clipsToBounds为true不会显示阴影
//shadowView.clipsToBounds = true
view.addSubview(shadowView)
}
2.可以自定义一个view,重写drawRect:方法
主要代码:
override func drawRect(rect: CGRect) {
//get contextRef
var context = UIGraphicsGetCurrentContext()
//rect
var pathRect = CGRectInset(self.bounds, self.bounds.size.width * 0.1, self.bounds.size.height * 0.1)
let cornerRaidus: CGFloat = 20
var rectanglePath = UIBezierPath(roundedRect: pathRect, cornerRadius: cornerRaidus)
CGContextSaveGState(context)
//set shadow
var shadow = UIColor.blackColor().CGColor
var shadowOffset = CGSizeMake(3, 3)
var shadowRadius : CGFloat = 5.0
CGContextSetShadowWithColor(context, shadowOffset, shadowRadius, shadow)
//fill color
UIColor.greenColor().setFill()
rectanglePath.fill()
CGContextRestoreGState(context)
}
效果为绿色view
类似的渐变色,transform都重写drawRect:可以自己定义.