贝塞尔曲线

使用BezierPath设置圆角和边框颜色

2018-11-21  本文已影响38人  leimeimei

为了避免离屏渲染,我用UIBezierPath给UIButton设置了圆角。但是给button的边框设置颜色时遇到了问题。最后在Stack Overflow上找到一个解决办法。
代码:

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(100, 100, 100, 100);
    [self.view addSubview:btn];
    
    // 设置曲线
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:btn.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(50, 50)];
    // 设置蒙层
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.frame = btn.bounds;
    layer.path = path.CGPath;
    btn.layer.mask = layer;
    // 设置一个和蒙层大小相同的layer,设置颜色和宽度,添加到button上
    CAShapeLayer *boderLayer = [CAShapeLayer layer];
    boderLayer.frame = btn.bounds;
    boderLayer.path = path.CGPath;
    boderLayer.strokeColor = [UIColor greenColor].CGColor;
    boderLayer.fillColor = [UIColor clearColor].CGColor;
    boderLayer.lineWidth = 1.f;
    [btn.layer addSublayer:boderLayer];
上一篇下一篇

猜你喜欢

热点阅读