Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

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

$
0
0

需求:

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开发者交流群:446310206



作者:qq_31810357 发表于2017/6/20 15:06:20 原文链接
阅读:95 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>