UIView重写drawRect会导致视图不遵守masksToBounds

Can*_*ğlu 7 uiview drawrect ios ios6

我试图drawRect:在我的自定义视图中覆盖UIView 的方法.但是,我的视图的边界半径定义为:

    sub = [[[NSBundle mainBundle] loadNibNamed:@"ProfileView" owner:self options:nil] objectAtIndex:0];
    [self addSubview:sub];
    [sub setUserInteractionEnabled:YES];
    [self setUserInteractionEnabled:YES];
    CALayer *layer = sub.layer;
    layer.masksToBounds = YES;
    layer.borderWidth = 5.0;
    layer.borderColor = [UIColor whiteColor].CGColor;
    layer.cornerRadius = 30.0;
Run Code Online (Sandbox Code Playgroud)

这完美地工作,并在我的视图周围放置一个边框半径很好的边框(不要介意背面的对角线/直线白线,它们与此视图无关):

纠正一个

但是,当我尝试drawRect:在我的视图中覆盖该方法时,我可以看到黑色背景没有掩盖到边界.我没有做任何事情(目前),这里是我的代码:

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
}
Run Code Online (Sandbox Code Playgroud)

这是结果:

不正确的

我只改变了绘制方法.如何在保持视图遵循角半径蒙版的同时覆盖绘制方法?这是iOS中的错误还是我错过了什么?

Ale*_*fee 3

我不知道完整的答案,但我确实知道 UIView 的实现会drawLayer:inContext:根据您是否实现drawRect:而有所不同。也许屏蔽/裁剪边界是它所做的不同的事情之一。

您可以尝试通过多种方式解决您的问题:

  • 让你的背景透明:

        layer.backgroundColor = [UIColor clearColor].CGColor;
    
    Run Code Online (Sandbox Code Playgroud)
  • 将自己剪辑在您的自定义中drawRect:

    - (void)drawRect:(CGRect)rect {
        [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:30.0] addClip];
        [image drawInRect:rect];  // or whatever
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 明确地切出角落:

    CGContextBeginPath(c);
    CGContextAddArc(c, r, r, r, M_PI, 3*M_PI_2, 0);
    CGContextAddLineToPoint(c, 0, 0);
    CGContextClosePath(c);
    CGContextClip(c);
    [[UIColor grayColor] setFill];
    UIRectFill(rect);
    
    Run Code Online (Sandbox Code Playgroud)

我从 WWDC 2010 的精彩演示中窃取了最后两条建议:iPhone OS 上的高级性能优化此索引页列出了视频- 令人烦恼的是,没有直接链接)。