通过代码设置UIView的任意一个角为圆角
先创建RectCorner 继承自UIView
.h代码
#import <UIKit/UIKit.h>
@interface RectCorner : UIView
/**
* 顶部圆角
*/
- (void)setCornerOnTop;
/**
* 底部圆角
*/
- (void)setCornerOnBottom;
/**
* 全部圆角
*/
- (void)setAllCorner;
@end
.m代码
#import "RectCorner.h"
@implementation RectCorner
- (void)setCornerOnTop {
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
cornerRadii:CGSizeMake(8.0, 8.0)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
- (void)setCornerOnBottom {
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)
cornerRadii:CGSizeMake(8.0, 8.0)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
- (void)setAllCorner {
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
cornerRadius:8.0];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
- (void)setNoneCorner {
self.layer.mask = nil;
}
@end
使用方法
#import "ViewController.h"
#import "RectCorner.h"
@interface ViewController ()
@property (nonatomic,strong)RectCorner *rc;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//四角全不为圆角
RectCorner *rc = [[RectCorner alloc]init];
rc.backgroundColor = [UIColor magentaColor];
rc.frame = CGRectMake(100, 100, 100, 100);
[self.view addSubview:rc];
[rc setAllCorner];
//底部两个角为圆角
RectCorner *rc1 = [[RectCorner alloc]init];
rc1.backgroundColor = [UIColor magentaColor];
rc1.frame = CGRectMake(100, 220, 100, 100);
[self.view addSubview:rc1];
[rc1 setCornerOnBottom];
//顶部两个角为圆角
RectCorner *rc2 = [[RectCorner alloc]init];
rc2.backgroundColor = [UIColor magentaColor];
rc2.frame = CGRectMake(100, 350, 100, 100);
[self.view addSubview:rc2];
[rc2 setCornerOnBottom];
//任意角为圆角
UIView *bgView = [[UIView alloc]init];
bgView.frame = CGRectMake(220, 200, 50, 50);
bgView.backgroundColor = [UIColor purpleColor];
bgView.userInteractionEnabled = YES;
[self.view addSubview:bgView];
/**
UIRectCornerTopLeft 上左
UIRectCornerTopRight上右
UIRectCornerBottomRight下右
UIRectCornerBottomRight下右
*/
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bgView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = bgView.bounds;
maskLayer.path = maskPath.CGPath;
bgView.layer.mask = maskLayer;
}
@end