為UIView設(shè)置陰影效果
陰影效果的實(shí)現(xiàn),蘋果提供了很好的實(shí)現(xiàn)方式,主要是layer層的繪制,具體的原理,可以查詢資料.
注意一定不要寫野宜,否則不會(huì)顯示陰影
self.view.layer.masksToBounds = YES;
或者
self.view.layer.clipsToBounds = YES;
1.最直接,也是比較簡(jiǎn)單的方式:效果如紅色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不會(huì)顯示陰影
//shadowView.clipsToBounds = true
view.addSubview(shadowView)
}
2.可以自定義一個(gè)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:可以自己定義.