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

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

4

2 回答 2

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];
于 2012-10-08T23:05:24.273 回答
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;
于 2015-04-16T21:40:49.290 回答