2

我只想在一侧设置 UIButton 和圆角的边框

我使用这段代码:

//set rounded corners on top
UIBezierPath *maskPath =  [UIBezierPath bezierPathWithRoundedRect:self.scanButton.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(10.0, 10.0)];

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.scanButton.bounds;
maskLayer.path = maskPath.CGPath;

self.scanButton.layer.mask = maskLayer;

// set border
self.scanButton.layer.borderColor = [UIColor blackColor].CGColor;
self.scanButton.layer.borderWidth = 2.0f;
[self.scanButton.layer setMasksToBounds:YES];

在此处输入图像描述

如何在顶角制作正确的边框?

4

3 回答 3

7

斯威夫特 2.0 版本

边框的角正在剪裁,因为您可能已经在 UIView 本身上设置了视图的背景颜色。更好的方法是直接在图层上设置填充颜色。这可以这样做:

let button = ... // your existing UIButton
let borderLayer = CAShapeLayer()
borderLayer.strokeColor = UIColor.blackColor().CGColor
borderLayer.fillColor = UIColor.yellowColor().CGColor
borderLayer.borderWidth = 2.0

let borderPath = UIBezierPath(roundedRect: button.bounds,
    byRoundingCorners: [.TopLeft, .TopRight],
    cornerRadii: CGSize(width:10.0, height: 10.0))
    borderLayer.path = borderPath.CGPath

button.layer.insertSublayer(borderLayer, atIndex: 0)

上面会给你这个没有剪角的结果:

示例按钮

我已经使用这种方法组合了一个 UIButton 子类,可以在按钮的每个角分别设置边框半径,在这里查看:https ://gist.github.com/alexpls/95279b3f9a2da7f2d7bf ,希望它有所帮助!

于 2015-10-20T11:30:18.490 回答
2

您最好使用自定义绘图继承 UIButton 并覆盖 drawRect:。你需要实现一个 CGContext 并添加你的 UIBezierPath 然后描边它。不记得是否需要先将其设为 CGPath,但我不这么认为。

于 2013-10-07T17:14:21.650 回答
1

看看下面的答案 - Stroke masked CALayer in iOS他使用蒙版和形状图层的组合来绘制这样的自定义边框。您需要关闭蒙版图层的常规边框。

于 2013-10-07T21:49:46.897 回答