2012-10-08 75 views
11

我有一个自定义按钮,我想让它的左上角看起来像普通的圆形矩形。在左上角创建自定义的圆角矩形按钮角点?

我发现代码,使各个角落轮:

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

此代码不能正常工作。整个按钮消失。

+0

这里是你如何使用UIBezierPath告诉保留哪个角落/上一个UIView面具类似的提问/回答:http://stackoverflow.com/questions/10995226/how-to -ma-half-rounded-top-corner-rounded-texview-with-border – Brayden

+0

我使用了那里提供的代码。但它不起作用。我将代码添加到问题的最后。你能帮我@布雷登吗? – Ali

回答

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

谢谢,看看这一行:'[_myButton.layer addSublayer:shapePath];'你的意思'shapeLayer'而不是shapePath? – Ali

+0

我其实用shapeLayer试过,但没有奏效。 – Ali

+1

这就是我的意思。 “没有工作”是什么意思? – AliSoftware

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;