iOS圓角和陰影並存
阿新 • • 發佈:2019-01-06
當我搬起磚頭時,我無法擁抱你;當我放下磚頭時,我無法養活你!虐不虐,你就說虐不虐~
扯得有點多了,迴歸主題~
先貼一下效果圖
圓角和陰影無法共存的原因就是因為這句程式碼。Because shadow is an effect done outside the View, and that masksToBounds set to YES will tell the UIView not to draw everything that is outside itself.
根據我沒過四級的英語水平,這句話的意思就是,圓角都是我給你割出來的,圓角外面的陰影自然也割掉了~
所以,這麼看來,圓角與陰影不能並存啊(僅限這種圓角實現的方式)
_tableView.layer.masksToBounds = YES;
那麼我們怎麼實現呢?
之前在動畫總結的時候講到CALayer最簡單的理解方式就把它當做一個檢視,可以直接加在view上。而我們需要的陰影,則正是它的屬性。那麼我們直接在View上加一個CALayer,並作出陰影效果,讓它位於我們要新增的陰影view的下面即可。
下面是程式碼,很簡單的幾行~
CALayer *subLayer=[CALayer layer];
CGRect fixframe = _tableView.frame ;
subLayer.frame= fixframe;
subLayer.cornerRadius=8;
subLayer.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.8].CGColor;
subLayer.masksToBounds=NO;
subLayer.shadowColor = [UIColor blackColor].CGColor;//shadowColor陰影顏色
subLayer.shadowOffset = CGSizeMake(3,2);//shadowOffset陰影偏移,x向右偏移3,y向下偏移2,預設(0, -3),這個跟shadowRadius配合使用
subLayer.shadowOpacity = 0.8;//陰影透明度,預設0
subLayer.shadowRadius = 4;//陰影半徑,預設3
[self.bkgView.layer insertSublayer:subLayer below:_tableView.layer];
這樣我們的tableview下面便有了陰影了~
內容有點少,把繪製三角檢視的程式碼也貼上吧
- (void)drawRect:(CGRect)rect {
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ref, self.bounds.origin.x+10, 0); // 起點
CGContextAddLineToPoint(ref, self.bounds.origin.x, 10); // 連線
CGContextAddLineToPoint(ref, 20, 10); // 連線
CGContextClosePath(ref); // 閉攏
[THEME_COLOR setFill];// 背景填充顏色
[THEME_COLOR setStroke]; // 連線顏色 即邊框顏色
CGContextDrawPath(ref, kCGPathFillStroke);
}