关于UIView没有设置backgroundColor引发的惨案
zyhiang0909先贴代码 `@implementation TestView
static int count = 0;
(id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// self.backgroundColor = [UIColor redColor];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(test) userInfo:nil repeats:YES];} return self; }
// Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation.
(void)drawRect:(CGRect)rect {
// Drawing code\
[[UIColor greenColor] setFill];
[[NSString stringWithFormat:@"%d",count] drawInRect:self.bounds withFont:[UIFont systemFontOfSize:15]]; }
(void) test {
count++;
[self setNeedsDisplay];
}
我把initWithFrame里设置背景颜色注释掉,发现绘制出来的都是重叠的,而设置设置背景颜色后,却正常了,这是为什么呀?
@sycx 大神~~~~~求救
@tinyfool 能解答一下嘛?
你的-drawRect里 [[UIColor greenColor] setFill]; 只是设置Fill颜色,
执行具体Fill还得调用CGContextFillRect(UIGraphicsGetCurrentContext(), self.bounds);
UIView 有个属性opaque, 默认为 YES
UIView 还有个属性clearsContextBeforeDrawing, 默认为 YES
- 当
opaque=YES时, 系统调用-drawRect:前,不会清除以前内容 - 当
opaque= NO时, 系统调用-drawRect:前,会根据clearsContextBeforeDrawing属性做不同行为clearsContextBeforeDrawing = YES, 则清除内容,以透明像素填充clearsContextBeforeDrawing = YES, 则不清除内容
以上是context清理,之后是backgroundColor填充context,默认为nil,相当于不做任何操作;
当你指定一个颜色后,系统会用backgroundColor填充context, 自然就擦除了你之前的内容。