UIView重写drawRect导致视图不遵守masksToBounds [英] UIView overriding drawRect causes view not to obey masksToBounds
问题描述
我试图在自定义视图中覆盖UIView的 drawRect:
方法。但是,我的视图的边界半径定义为:
I am trying to override the drawRect:
method of UIView in my custom view. However, my view has a border radius defined as:
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;
这完美无缺,并在我的视图周围放置了一个带边框半径的漂亮边框(不介意背面的对角线/直白线,它们与此视图无关):
This works perfectly and places a nice border with a border radius around my view (don't mind the diagonal/straight white lines at the back, they have nothing to do with this view):
然而,当我尝试覆盖 drawRect:
在我看来,我可以看到黑色背景没有掩盖到边界。我不做任何(目前),这是我的代码:
However, when I try to override the drawRect:
method in my view, I can see a black background not masking to bounds. I don't do anything (currently), here is my code:
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
}
结果如下:
我'除了绘制方法之外什么都没改变。如何在保持视图遵循角半径蒙版的同时覆盖绘制方法?这是iOS中的错误还是我错过了什么?
I've changed nothing but the draw method. How can I override the draw method while keeping my view obey the corner radius mask? Is this a bug in iOS or am I missing something?
推荐答案
我不知道完整的答案,但我知道UIView的 drawLayer:inContext:
的实现方式不同,具体取决于你是否实现了 drawRect:
。也许掩盖/限制边界是其中一种不同的方式。
I don't know the full answer, but I do know that UIView's implementation of drawLayer:inContext:
works differently depending on whether you have implemented drawRect:
or not. Perhaps masking/clipping to bounds is one of those things it does differently.
您可以尝试通过多种方式解决问题:
You can try solving your issue a number of ways:
-
让你的背景透明:
make your background transparent:
layer.backgroundColor = [UIColor clearColor].CGColor;
将自己剪辑到自定义 drawRect:
:
- (void)drawRect:(CGRect)rect {
[[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:30.0] addClip];
[image drawInRect:rect]; // or whatever
}
明确划出角落:
carve out the corners explicitly:
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);
我偷了这个伟大的最后2条建议来自WWDC 2010的演示: iPhone OS上的高级性能优化(视频列在< a href =https://developer.apple.com/videos/wwdc/2010/\"rel =nofollow>这个索引页面 - 烦人的,没有直接的链接。)
I stole those last 2 suggestions from this great presentation from WWDC 2010: Advanced Performance Optimization on iPhone OS (video listed at this index page -- annoyingly, no direct link).
这篇关于UIView重写drawRect导致视图不遵守masksToBounds的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!