2015-02-11 116 views
1

我正在使用此代码使我的顶角四舍五入。自动布局约束和CALayer问题

- (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners 
{ 
    UIBezierPath *rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds 
                byRoundingCorners:corners 
                 cornerRadii:CGSizeMake(5.0, 5.0)]; 
    CAShapeLayer *shape = [[CAShapeLayer alloc] init]; 
    [shape setPath:rounded.CGPath]; 
    view.layer.mask = shape; 
} 

然后在上海华法initWithFrame我有这样的:

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero]; 
[self setMaskTo:imageView byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight]; 

但作为它的结果,我没有看到图像。我正在使用自动布局约束,它可以正确工作,如果我不使用上述圆角方法,则会看到图像。但是如果我使用它,我看不到图像。

似乎如果使用我的视图的绘制矩形回调放置图像,我可以设置圆角。但在这种情况下,如果视图包含其他视图会加重四舍五入到所有子视图,如果我将循环它:

它的工作原理,但对于课程的所有子视图:

- (void)drawRect:(CGRect)rect { 
    // Drawing code 

    for (UIView *view in self.subviews) 
    { 
     [self setMaskTo:view byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight]; 
    } 

} 

- (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners 
{ 
    UIBezierPath *rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds 
                byRoundingCorners:corners 
                 cornerRadii:CGSizeMake(5.0, 5.0)]; 
    CAShapeLayer *shape = [[CAShapeLayer alloc] init]; 
    [shape setPath:rounded.CGPath]; 
    view.layer.mask = shape; 
} 

那么如何检测时的图像视图已经得到框架,我想在开始时帧是零CALayer不理解如何与视图交互。

回答

1

发生这种情况是因为您使用CGRectZero框架实例化视图,然后将该边界用于遮罩,因此视图中的任何内容都不在遮罩内,因此不会显示任何内容。

作为变通,你可以设置不同的标签来UIImageView的实例比0,并在子视图搜索该

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero]; 
imageView.tag = 111; //or any other number you want 

- (void)drawRect:(CGRect)rect { 
// Drawing code 

for (UIView *view in self.subviews) 
{ 
    if (view.tag==111){[self setMaskTo:view byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight]; 
}} 

} 

- (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners 
{ 
UIBezierPath *rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds 
               byRoundingCorners:corners 
                cornerRadii:CGSizeMake(5.0, 5.0)]; 
CAShapeLayer *shape = [[CAShapeLayer alloc] init]; 
[shape setPath:rounded.CGPath]; 
view.layer.mask = shape; 
} 
0

如果我理解正确的话,你希望你的UIView,其中包含内部的图像,在顶部有圆角,对吗?然后,您可以调整layoutSubviews中的遮罩层大小。

喜欢的东西:

- (void)awakeFromNib { 
    [super awakeFromNib]; 

    [self setMaskTo:self byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight]; 
} 

- (void)layoutSubviews { 
    [super layoutSubviews]; 

    self.layer.mask.frame = self.layer.bounds; 
} 

- (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners { 
    UIBezierPath *rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds 
                byRoundingCorners:corners 
                 cornerRadii:CGSizeMake(5.0, 5.0)]; 
    CAShapeLayer *shape = [[CAShapeLayer alloc] init]; 
    [shape setPath:rounded.CGPath]; 
    view.layer.mask = shape; 
    view.layer.masksToBounds = YES; 
}