2012-10-08 119 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;