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

时间:2012-10-08 22:03:28

标签: ios objective-c cocoa-touch cashapelayer

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

我找到了使所有角落成圆形的代码:

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

enter image description here

如何修复代码以使其在左上角转动?


编辑:

_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];

此代码不起作用。整个按钮消失。

2 个答案:

答案 0 :(得分:23)

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

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 :(得分: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;