需求:
1.日常我们在切控件圆角时会遇到想切任意圆角?
2.切过圆角带边框和不带边框的选择?
那么今天我们就用Objective-C和Swift都给它实现了:
OC代码:
UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 70)]; myLabel.text = @"Hi,小韩哥!"; myLabel.font = [UIFont systemFontOfSize:20.0]; myLabel.textAlignment = NSTextAlignmentCenter; [self.view addSubview:myLabel]; CGFloat radius = 21.0f; UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:myLabel.bounds byRoundingCorners:UIRectCornerTopRight|UIRectCornerBottomRight cornerRadii:CGSizeMake(radius, radius)]; CAShapeLayer * mask = [[CAShapeLayer alloc] init]; mask.lineWidth = 5; mask.lineCap = kCALineCapSquare; // 带边框则两个颜色不要设置成一样即可 mask.strokeColor = [UIColor redColor].CGColor; mask.fillColor = [UIColor yellowColor].CGColor; mask.path = path.CGPath; [myLabel.layer addSublayer:mask];
Swift代码:
override func viewDidLoad() { super.viewDidLoad() view.addSubview(myLabel); myLabel.layer.addSublayer(myLayer); } private lazy var myLabel:UILabel = { let label = UILabel.init(frame: CGRect.init(x: 100, y: 100, width: 200, height: 70)); label.text = "Hi,小韩哥!"; label.textAlignment = .center; return label; }() private lazy var myLayer:CAShapeLayer = { let path = UIBezierPath.init(roundedRect: self.myLabel.bounds, byRoundingCorners: [.topRight , .bottomRight] , cornerRadii: self.myLabel.bounds.size); let layer = CAShapeLayer.init(); layer.path = path.cgPath; layer.lineWidth = 5; layer.lineCap = kCALineCapSquare; layer.strokeColor = UIColor.red.cgColor; // 注意直接填充layer的颜色,不需要设置控件view的backgroundColor layer.fillColor = UIColor.yellow.cgColor; return layer; }()
效果:
第三种思路:
Demo : https://github.com/iOS-OC-Developer/JQRadiusView
更多惊喜:手机加iOS开发者交流群:446310206