先贴代码 `@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里设置背景颜色注释掉,发现绘制出来的都是重叠的,而设置设置背景颜色后,却正常了,这是为什么呀?
你的-drawRect里 [[UIColor greenColor] setFill]; 只是设置Fill颜色,
执行具体Fill还得调用CGContextFillRect(UIGraphicsGetCurrentContext(), self.bounds);
3楼 @sycx 即使不用CGContextFillRect(UIGraphicsGetCurrentContext(), self.bounds);绘制出字体也是绿色的,我刚用CGContextFillPath(context);效果也是一样,问题就是出在我initWithFrame的时候没有设置这个view的背景颜色,代码的意图是一个定时器,然后绘制在view上,不加背景颜色的现象是2覆盖在1上,3,4,5....接着都是一个个覆盖上去的,我就是不知道为什么不设背景会出现这个效果。。。
UIView 有个属性opaque, 默认为 YES
UIView 还有个属性clearsContextBeforeDrawing, 默认为 YES
opaque=YES时, 系统调用-drawRect:前,不会清除以前内容opaque= NO时, 系统调用-drawRect:前,会根据clearsContextBeforeDrawing属性做不同行为
clearsContextBeforeDrawing = YES, 则清除内容,以透明像素填充clearsContextBeforeDrawing = YES, 则不清除内容以上是context清理,之后是backgroundColor填充context,默认为nil,相当于不做任何操作;
当你指定一个颜色后,系统会用backgroundColor填充context, 自然就擦除了你之前的内容。
5楼 @sycx 想问下,当UIView 的属性 opaque=YES 时所产生的行为和当UIView的属性opaque=No而clearsContextBeforeDrawing = YES时所产生的行为一样 ,都是不会清除以前内容