借助CAShapeLayer可以实现指定视图任意角的圆角,步骤如下
- 设置视图的宿主图层为CAShapeLayer
+(Class)layerClass {
return [CAShapeLayer class];
}
- 构造圆角图像的Path
CornerButton *button = [[CornerButton alloc] init];
[button setTitle:@"hello" forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
button.frame = CGRectMake(50, 50, 100, 30);
CAShapeLayer *layer = (CAShapeLayer *)button.layer;
CGRect rect = button.bounds;
CGSize raddii = CGSizeMake(20, 20);
UIRectCorner corners = UIRectCornerTopLeft|UIRectCornerTopRight;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:raddii];
layer.path = path.CGPath;
视图默认的宿主图层为CALayer,CAShapeLayer继承与CALayer,设置宿主图层为CAShapeLayer不会影响源视图的绘制等效果。