圆角
cornerRadius
iOS开发中各种圆角也随处可见,最简单给控件添加圆角的方式就是给视图的layer设置corner属性了:
1 2
| self.blueView.layer.cornerRadius = 5.f self.blueView.layer.masksToBounds = YES
|
这种方式会带来两个问题:
当图片数量比较多的时候,这种添加圆角方式特别消耗性能,比如在UITableViewCell添加过多圆角的话,甚至会带来视觉可见的卡顿.
无法配置圆角数量(只能添加view的四个角全为圆角),无法配置某个圆角大小.
第一个问题实际上是由于数量太多的情况下,系统会频繁的调用GPU的离屏渲染(Offscreen Rendering)机制,导致内存损耗严重.更多关于离屏渲染的详解,可以看这里,本文不多赘述.
maskLayer
直接上代码:
1 2
| @property (weak, nonatomic) IBOutlet UIImageView *userHead; @property (nonatomic,strong) CAShapeLayer * userMaskLayer;
|
在ViewDidLoad中设置mask:self.userHead.layer.mask = [self userHeaderMask:self.userHead];
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| - (CALayer )userHeaderMask:(UIView )originalView{
CALayer * userMask = [CALayer layer]; userMask.frame = originalView.bounds;
CGFloat x = originalView.frame.size.width/2; CGFloat y = originalView.frame.size.height/2;
self.userMaskLayer = [CAShapeLayer layer]; self.userMaskLayer.bounds = originalView.bounds; self.userMaskLayer.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(x, y) radius:50 startAngle:0 endAngle:2*M_PI clockwise:YES].CGPath; self.userMaskLayer.position = CGPointMake(50, 50); [userMask addSublayer:self.userMaskLayer];
return userMask; }
|
原理:通过设置UIImageView的layer的mask属性。
UIBezierPath
第三个问题,我们可以使用UIBezierPath
来完美解决.以下是示例代码:
1 2 3 4 5 6 7 8 9 10 11 12
| UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.blueView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(20, 0)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.blueView.bounds;
maskLayer.path = maskPath.CGPath;
self.blueView.layer.mask = maskLayer;
self.blueView.layer.cornerRadius = 5.f; self.blueView.layer.masksToBounds = YES;
|
想要配置某个角为圆角的话,只需要指定对应的UIRectCorner
即可
以下是显示效果:
阴影
layer
直接上代码:
1 2 3 4
| _imageView.layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色 _imageView.layer.shadowOffset = CGSizeMake(4,4) _imageView.layer.shadowOpacity = 0.6 _imageView.layer.shadowRadius = 3
|
UIBezierPath
1 2 3 4 5 6 7 8 9 10 11
| UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:imageView.bounds];
imageView.layer.masksToBounds = NO
imageView.layer.shadowColor = [UIColor blackColor].CGColor;
imageView.layer.shadowOffset = CGSizeMake(0.0f, 5.0f)
imageView.layer.shadowOpacity = 0.5f
imageView.layer.shadowPath = shadowPath.CGPath;
|