iOS UIView 选择性倒角
有些APP中会有卡券,卡券做成了选择性倒角,例如左上,右上倒角。非常美观。看一下iOS的实现:
#import "Masonry.h"
@interface WJWDaojiaoViewController ()
@property (nonatomic, strong) UIView *myView;
@end
@implementation WJWDaojiaoViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"视图倒角";
[self configUI];
}
- (void)configUI {
[self.view addSubview:self.myView];
self.view.backgroundColor = [UIColor redColor];
// self.myView.backgroundColor = [UIColor redColor];
[self.myView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view).offset(84 + 10);
make.left.equalTo(self.view);
make.right.equalTo(self.view);
make.height.mas_equalTo(100);
}];
}
- (void)viewDidLayoutSubviews {
CGRect oldRect = _myView.bounds;
oldRect.size.width = [UIScreen mainScreen].bounds.size.width;
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:oldRect byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.path = maskPath.CGPath;
maskLayer.frame = oldRect;
_myView.layer.mask = maskLayer;
}
- (UIView *)myView {
if (!_myView) {
_myView = [[UIView alloc] init];
_myView.backgroundColor = [UIColor blueColor];
}
return _myView;
}
效果图:
需要注意的是,myView用masonry在configUI中布局,直接在布局后设置倒角是不行的。因为布局结束系统并不会立即更新控件的frame,frame是在-viewDidLayoutSubviews()方法执行后确定的,所以设置倒角在这里。
而且把布局方法放在 -viewDidLayoutSubviews() 中也是不行的。想想为什么。