iOS 圆角cornerRadius边框border阴影Shadow

Posted wuwuFQ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 圆角cornerRadius边框border阴影Shadow相关的知识,希望对你有一定的参考价值。

圆角cornerRadius

先看一下官网解释

Setting the radius to a value greater than 0.0 causes the layer to begin drawing rounded corners on its background. By default, the corner radius does not apply to the image in the layer’s contents property; it applies only to the background color and border of the layer. However, setting the masksToBounds property to YES causes the content to be clipped to the rounded corners.
The default value of this property is 0.0.

白话翻译:

cornerRadius是对背景的一个切割渲染,和内容无关,所以内容超过以后,圆角就会失效,这个时候需要自己注意子视图 或者设置 masksToBounds=YES 直接切割视图

普通切圆角:

 self.layer.masksToBounds = NO;
 self.layer.cornerRadius = 8;

花式切圆角:

 UIRectCorner corner = UIRectCornerTopLeft | UIRectCornerTopRight;
 CAShapeLayer *maskLayer = [CAShapeLayer layer];
 UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(e.radius, e.radius)];
 maskLayer.path = maskPath.CGPath;
 maskLayer.frame = self.bounds;
 self.layer.mask = maskLayer;
 //layer.mask:特殊的CALayer,maskPath外的视图不会显示

边框border

普通边框:

self.layer.borderWidth = 1self.layer.borderColor = [UIColor redColor].CGColor;

花式边框:

UIRectCorner corner = UIRectCornerAllCorners;
CAShapeLayer *borderLayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(5, 5)];
borderLayer.path = path.CGPath;
borderLayer.strokeColor = [UIColor colorFromHexString:e.borderColor].CGColor;
borderLayer.fillColor = [UIColor clearColor].CGColor;
borderLayer.lineWidth = e.borderWidth;
borderLayer.frame = self.bounds;
[self.layer addSublayer:borderLayer];

阴影Shadow

普通阴影:

self.layer.shadowOpacity = 1;
self.layer.shadowColor = [UIColor lightGrayColor].CGColor;
self.layer.shadowOffset = CGSizeZero;

花式阴影:

self.layer.shadowOpacity = 1;
self.layer.shadowColor = [UIColor lightGrayColor].CGColor;
CGFloat pathX = -3;
CGFloat pathY = -3;
CGFloat pathWidth = self.frame.size.width + 6;
CGFloat pathHeight = self.frame.size.height + 6;
CGRect pathRect = CGRectMake(pathX, pathY, pathWidth, pathHeight);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:pathRect cornerRadius:0];
self.layer.shadowPath = path.CGPath;

总结:想要圆角、边框、阴影共存,用花式!

以上是关于iOS 圆角cornerRadius边框border阴影Shadow的主要内容,如果未能解决你的问题,请参考以下文章

iOS 设置控件的边框圆角

iOS 设置控件的边框圆角

ios中设置UIButton圆角,添加边框

iOS中设置圆角的方式

iOS设置圆角的四种方法

iOS核心动画之视觉效果