為UIView設置陰影效果


陰影效果的實現,蘋果提供了很好的實現方式,主要是layer層的繪制,具體的原理,可以查詢資料.

1.最直接,也是比較簡單的方式:效果如紅色view

 1 func addShadowView(){
 2         let shadowView = UIView(frame: CGRectMake(100, 100, 100, 100))
 3         shadowView.backgroundColor = UIColor.redColor()
 4         //setShadow
 5         shadowView.layer.cornerRadius = 5;
 6         shadowView.layer.shadowColor = UIColor.blackColor().CGColor
 7         shadowView.layer.shadowOffset = CGSizeMake(5, 10)
 8         shadowView.layer.shadowOpacity = 1.0
 9         shadowView.layer.shadowRadius = 5;
10         //clipsToBounds為true不會顯示陰影
11         //shadowView.clipsToBounds = true
12         view.addSubview(shadowView)
13         
14         
15     }

 

2.可以自定義一個view,重寫drawRect:方法

主要代碼:

 1 override func drawRect(rect: CGRect) {
 2         //get contextRef
 3         var context = UIGraphicsGetCurrentContext()
 4         //rect
 5         var pathRect = CGRectInset(self.bounds, self.bounds.size.width * 0.1, self.bounds.size.height * 0.1)
 6         let cornerRaidus: CGFloat = 20
 7         var rectanglePath = UIBezierPath(roundedRect: pathRect, cornerRadius: cornerRaidus)
 8         CGContextSaveGState(context)
 9         //set shadow
10         var shadow = UIColor.blackColor().CGColor
11         var shadowOffset = CGSizeMake(3, 3)
12         var shadowRadius : CGFloat = 5.0
13         
14         
15         CGContextSetShadowWithColor(context, shadowOffset, shadowRadius, shadow)
16         //fill color
17         UIColor.greenColor().setFill()
18         rectanglePath.fill()
19         CGContextRestoreGState(context)
20     }

效果為綠色view

類似的漸變色,transform都重寫drawRect:可以自己定義.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM