iOS 圆角cornerRadius、边框border、阴影Shadow

本文详细介绍了如何在iOS中为视图设置圆角、边框和阴影,包括普通方法和复杂技巧。通过设置layer的cornerRadius属性实现圆角,但注意内容不会自动被裁剪,需要结合masksToBounds属性使用。对于边框,可以设置不同颜色和宽度,以及自定义边框形状。同时,讲解了阴影的设置,包括普通阴影和复杂阴影的实现。总结中强调,若要使圆角、边框和阴影共存,需要采用更复杂的设置方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

圆角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;

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wuwuFQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值