UIView子类绘制背景尽管完全空drawRect: - 为什么? [英] UIView subclass draws background despite completely empty drawRect: - why?
问题描述
所以,我有一个自定义的UIView子类,使绘制圆角边缘。事情绘制完美,但背景总是填充整个边界,尽管剪切到一个路径第一。边框也会在矩形背景上方绘制 ,尽管我在drawRect:前绘制边框。所以我删除了drawRect:的整个内容,现在几乎是空的 - 但是背景被绘制了!
So, I have a custom UIView subclass which enables drawing of rounded edges. The thing draws perfectly, however the background always fills the whole bounds, despite clipping to a path first. The border also draws above the rectangular background, despite the fact that I draw the border in drawRect: before the background. So I removed the whole content of drawRect:, which is now virtually empty - nevertheless the background gets drawn!
任何人都有解释?我在Interface Builder中设置了backgroundColor。谢谢!
Anybody an explanation for this? I set the backgroundColor in Interface Builder. Thanks!
推荐答案
很抱歉这个独白。 :)
Sorry for this monologue. :)
事情是,UIView的图层显然绘制了背景,它独立于 drawRect:
。这就是为什么你不能通过重写 drawRect:
来删除背景。
The thing is that the UIView's layer apparently draws the background, which is independent from drawRect:
. This is why you can't get rid of the background by overriding drawRect:
.
code> - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 并使图层绘制任何你想要的,或者你覆盖 - )setBackgroundColor:(UIColor *)newColor
,并且不要将 newColor 指定给 backgroundColor ,而是指定给自己的ivar,如 myBackgroundColor 。然后,您可以在drawRect中使用 myBackgroundColor ;
You can either override - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
and make the layer draw whatever you want, or you override - (void) setBackgroundColor:(UIColor *)newColor
and don't assign newColor to backgroundColor, but to your own ivar, like myBackgroundColor. You can then use myBackgroundColor in drawRect; to draw the background however you like.
覆盖 setBackgroundColor:
定义一个背景颜色的实例变量,例如 myBackgroundColor 。在你的init方法中,设置真实的背景颜色为clearColor:
Define an instance variable to hold your background color, e.g. myBackgroundColor. In your init methods, set the real background color to be the clearColor:
- (id) initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super init...])) {
[super setBackgroundColor:[UIColor clearColor]];
}
return self;
}
覆盖:
- (void) setBackgroundColor:(UIColor *)newColor
{
if (newColor != myBackgroundColor) {
[myBackgroundColor release];
myBackgroundColor = [newColor retain];
}
}
然后使用 myBackgroundColor 你的drawRect:方法。这样,您可以使用代码中从Interface Builder(或Xcode4)分配的颜色。
Then use myBackgroundColor in your drawRect: method. This way you can use the color assigned from Interface Builder (or Xcode4) in your code.
这篇关于UIView子类绘制背景尽管完全空drawRect: - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!