如果需要将UIView的4个角全部都为圆角,只需设置其Layer
的cornerRadius
属性即可(项目需要使用QuartzCore框架)。而若要指定某几个角(小于4)为圆角而别的不变时,这种方法就不好用了。
使用UIBezierPath,下面给出一段示例代码。
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
view.backgroundColor = [UIColor greenColor];
[self.view addSubview:view];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = view.bounds;
maskLayer.path = maskPath.CGPath;
view.layer.mask = maskLayer;
其中,
byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight
指定了需要成为圆角的角。该参数是UIRectCorner类型的,可选的值有:
* UIRectCornerTopLeft
* UIRectCornerTopRight
* UIRectCornerBottomLeft
* UIRectCornerBottomRight
* UIRectCornerAllCorners
从名字很容易看出来代表的意思,使用“|”来组合就好了。
UITableView中使用
在UITableViewCell中实现第一个Cell和最后一个Cell上下圆角,效果如下:
代码:
@property (nonatomic, strong) NSIndexPath *indexPath; //当前index
@property (nonatomic, assign) NSUInteger dataCount; //总数
@property (nonatomic, strong) UIView *bgView; //自定义的背景View
- (void)mask {
BOOL isFirst = self.indexPath.row == 0;
BOOL isLast = self.indexPath.row == self.dataCount-1;
if (isFirst || isLast) {
UIRectCorner corner = isLast ? UIRectCornerBottomLeft | UIRectCornerBottomRight : UIRectCornerTopLeft | UIRectCornerTopRight;
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bgView.layer.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(8, 8)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bgView.bounds;
maskLayer.path = maskPath.CGPath;
self.bgView.layer.mask = maskLayer;
}
}
//需要重写drawRect才有效
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
[self mask];
}