iOS中 切圆角,任意几个角(带边框,不带边框)__OC和Swift版本 韩俊强的博客

需求:

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;
        
    }()

效果:

iOS中 切圆角,任意几个角(带边框,不带边框)__OC和Swift版本 韩俊强的博客

iOS中 切圆角,任意几个角(带边框,不带边框)__OC和Swift版本 韩俊强的博客

第三种思路:


iOS中 切圆角,任意几个角(带边框,不带边框)__OC和Swift版本 韩俊强的博客

Demo : https://github.com/iOS-OC-Developer/JQRadiusView


iOS中 切圆角,任意几个角(带边框,不带边框)__OC和Swift版本 韩俊强的博客

更多惊喜:手机加iOS开发者交流群:446310206



上一篇:人工智能、机器学习、深度学习的区别在哪?


下一篇:标准化是“互联网+医疗”发展基础