如何在左上角创建自定义圆角矩形按钮?

11

我有一个自定义按钮,我想让它的左上角边框看起来像普通的圆角矩形。

我找到了可以使所有角都变成圆角的代码:

_myButton.layer.cornerRadius = 8;
_myButton.layer.borderWidth = 0.5;
_myButton.layer.borderColor = [UIColor grayColor].CGColor;
_myButton.clipsToBounds = YES;

图片描述

如何修正代码,使其仅在左上角处变为圆角?


编辑:

_myButton.layer.borderWidth = 2;
_myButton.layer.borderColor = [UIColor blackColor].CGColor;

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_myButton.bounds
                                                    byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight
                                                        cornerRadii:CGSizeMake(7.0, 7.0)];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

maskLayer.frame = _myButton.bounds;
maskLayer.path = maskPath.CGPath;
_myButton.layer.mask = maskLayer;
[maskLayer release];

这段代码无法正常工作。整个按钮会消失。


这里有一个类似的问题/答案,介绍了如何使用UIBezierPath来确定UIView上哪些角落需要保留/遮罩:https://dev59.com/j2TWa4cB1Zd3GeqPHd__ - Brayden
我使用了那里提供的代码,但它不起作用。我将代码添加到问题的末尾。@Brayden,你能帮我吗? - Ali
2个回答

23
你几乎做到了,但是,在构建CAShapeLayer之后,使用它将自身作为子层添加到按钮的图层中,而不是作为透明蒙版来隐藏按钮的某些部分(在这种情况下,是角落)。

你几乎做到了,但是,在构建CAShapeLayer之后,使用它将自身作为子层添加到按钮的图层中,而不是作为透明蒙版来隐藏按钮的某些部分(在这种情况下,是角落)。

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(10,300,300,40);
[button setTitle:@"Hey" forState:(UIControlStateNormal)];
[button setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];

UIBezierPath *shapePath = [UIBezierPath bezierPathWithRoundedRect:button.bounds
                                                byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight
                                                      cornerRadii:CGSizeMake(7.0, 7.0)];

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = button.bounds;
shapeLayer.path = shapePath.CGPath;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.strokeColor = [UIColor blackColor].CGColor;
shapeLayer.lineWidth = 2;
[button.layer addSublayer:shapeLayer];

[self.view addSubview:button];

1
那就是我想说的,抱歉。你所说的“没有工作”,是指什么?它看起来像什么? - AliSoftware
你确定在设置按钮的框架后创建了图层吗?也许当你创建shapePath并设置CAShapeLayerframe时,你使用了错误的值,因为_myButtonframe还没有设置到正确的值? - AliSoftware
实际上,我只是在我的当前项目的viewDidLoad中非常快速地放置了我的代码,但我只是复制粘贴了我写的内容。我会在我的回答中添加每一行周围的代码。 - AliSoftware
是的,我是。我刚刚复制了你的代码,但如果它能为你工作,请将项目发送给我。非常感激。 - Ali
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/17721/discussion-between-ali-and-alisoftware - Ali
显示剩余4条评论

1
CAShapeLayer * positiveCorner = [CAShapeLayer layer];
positiveCorner.path = [UIBezierPath bezierPathWithRoundedRect: self.button.bounds
                                            byRoundingCorners: UIRectCornerTopRight | UIRectCornerBottomRight
                                                  cornerRadii: (CGSize){5, 5}].CGPath;

self.button.layer.mask = positiveCorner;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接