Iphone 带圆角和边框的按钮
我想在UIButton上设置边框,只在一侧设置圆角 我使用以下代码:Iphone 带圆角和边框的按钮,iphone,ios,cocoa-touch,uibutton,rounded-corners,Iphone,Ios,Cocoa Touch,Uibutton,Rounded Corners,我想在UIButton上设置边框,只在一侧设置圆角 我使用以下代码: //set rounded corners on top UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.scanButton.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(10.0, 10.0)
//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];
如何在顶角创建适当的边框?您最好将UIButton子类化,并使用自定义图形覆盖drawRect:命令。您需要实现CGContext并添加UIBezierPath,然后对其进行笔划。我记不起是否需要先将其设置为CGPath,但我不这么认为 看看下面的答案-他使用掩模和形状层的组合来绘制这样的自定义边界。您需要关闭遮罩层的常规边框。Swift 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子类,其中可以在按钮的每个角落单独设置边界半径,请在此处查看:,希望它能有所帮助 虽然此链接可以回答问题,但最好在此处包含答案的基本部分,并提供链接供参考。如果链接页面更改,只有链接的答案可能会无效。谢谢,说得好。我已经更改了答案,因此它包含了一个针对所问问题的代码示例。