为UIButton Bezeir路径添加边框颜色

时间:2018-02-06 09:43:22

标签: objective-c uibutton

UIButton只有两个角落,即右上角和右下角,下面是:

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_nearmeButton.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomLeft) cornerRadii:CGSizeMake(20.0, 20.0)];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.view.bounds;
maskLayer.path  = maskPath.CGPath;
_nearmeButton.layer.mask = maskLayer;

但是如何给出与给定图像enter image description here相同的UIButton上方的边框颜色。

1 个答案:

答案 0 :(得分:1)

你走在正确的轨道上。您可以将其添加到按钮图层,而不是将路径设置为遮罩。基本上(或多或少)每个UIView都由CALayer支持。只需在笔触和填充上设置所需的颜色,然后将其添加到按钮图层,即可完成。

UIBezierPath *borderPath = [UIBezierPath bezierPathWithRoundedRect:_nearmeButton.bounds byRoundingCorners:(UIRectCornerTopRight | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20.0, 20.0)];

CAShapeLayer *borderLayer = [[CAShapeLayer alloc] init];
borderLayer.frame = self.view.bounds;
borderLayer.path  = borderPath.CGPath;
borderLayer.strokeColor = [UIColor redColor].CGColor;
borderLayer.fillColor = [UIColor clearColor].CGColor;
borderLayer.lineWidth = 1.0;
[_nearmeButton.layer addSublayer:borderLayer];

如果您的按钮尺寸发生变化,您还需要更新图层尺寸。