2016-01-20 99 views
3

我正在嘗試使用「UIBezierPath」將我的視角四捨五入。我只需要圍繞topRight和左上角。使用UIBezierPath的角半徑

我用下面的代碼

-(void)setMaskOnView:(UIView *)givenView 
    { 
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:givenView.bounds byRoundingCorners: (UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(10.0, 10.0)]; 
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; 
maskLayer.frame = givenView.bounds; 
maskLayer.path = maskPath.CGPath; 
givenView.layer.mask = maskLayer; 
} 

enter image description here

但我TopRight角不圓。

我用

UIRectCornerAllCorners

但它不圓我右角

enter image description here

任何事情我失蹤?

+1

你在哪裏調用'setMaskOnView'?可能在佈局完成之前。因此,邊界還沒有正確設置,並會/改變。 – luk2302

+0

givenView.bounds已更改爲givenView.superview.bounds,並檢查是否工作 –

+0

@ luk2302我在視圖中調用它DIDLoad –

回答

1

我建議不同的方法。加載帶圓角的圖像並設置爲CALayer的內容。將此圖層設置爲視圖圖層的蒙版。更新給定視圖的layoutSubivews或給定視圖控制器的viewDidLayoutSubviews中的遮罩層大小。

加載圖像層contenst

CALayer *maskLayer = [[CALayer alloc] init]; 
UIImage *maskImage = [UIImage imageNamed:@"mask_image.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil]; 
maskLayer.contents = (__bridge id _Nullable)(maskImage.CGImage); 

mainLayer.mask = maskLayer 

[編輯]在評論

或者使用CAShapeLayer或圖像作爲面膜,你必須調整遮蔽層,因此將有回答你的問題與蒙版圖層大小相同。如果我們正在談論UITableViewCell,請在layoutSubviews中創建您自己的衍生單元格並更新蒙版形狀。下面是示例代碼(MyTableCell從故事板加載):

@interface MyTableCell() 

@property (nonatomic, strong) CAShapeLayer *maskLayer; 

@end 

@implementation MyTableCell 

- (void)awakeFromNib 
{ 
    self.maskLayer = [[CAShapeLayer alloc] init]; 
    self.layer.mask = self.maskLayer; 
} 

- (void)layoutSubviews 
{ 
    [super layoutSubviews]; 
    self.maskLayer.path = [self maskPath].CGPath; 
} 

- (UIBezierPath *)maskPath 
{ 
    return [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners: (UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(10.0, 10.0)]; 

} 

@end 
0

我使用該亞類

.H

@interface UIView (custom) 

- (UIView *)setRoundedCorners:(UIRectCorner)corners withRadius:(CGFloat)radius; 

@end 

的.m

@implementation UIView (custom) 

    - (UIView *)setRoundedCorners:(UIRectCorner)corners withRadius:(CGFloat)radius 
    { 
     UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds 
                 byRoundingCorners:corners 
                  cornerRadii:CGSizeMake(radius, radius)]; 

     CAShapeLayer *maskLayer = [CAShapeLayer layer]; 

     maskLayer.frame = self.bounds; 

     maskLayer.path = maskPath.CGPath; 

     self.layer.mask = maskLayer; 

     return self; 
    } 
@end 

使用它像:

[YOURVIEW setRoundedCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight | UIRectCornerTopLeft | UIRectCornerTopRight withRadius:15];