iOS圆角和阴影并存

来源:互联网 发布:淘宝电子商务公司起名 编辑:程序博客网 时间:2024/05/18 12:41

当我搬起砖头时,我无法拥抱你;当我放下砖头时,我无法养活你!虐不虐,你就说虐不虐~

扯得有点多了,回归主题~

先贴一下效果图

效果图

圆角和阴影无法共存的原因就是因为这句代码。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);}