关于UIView没有设置backgroundColor引发的惨案

zyhiang0909 发布于 2013年10月25日 | 更新于 2013年10月28日
无人欣赏。

先贴代码 `@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里设置背景颜色注释掉,发现绘制出来的都是重叠的,而设置设置背景颜色后,却正常了,这是为什么呀?

共10条回复
zyhiang0909 回复于 2013年10月25日

@sycx 大神~~~~~求救

zyhiang0909 回复于 2013年10月25日

@tinyfool 能解答一下嘛?

sycx 回复于 2013年10月25日

你的-drawRect[[UIColor greenColor] setFill]; 只是设置Fill颜色,

执行具体Fill还得调用CGContextFillRect(UIGraphicsGetCurrentContext(), self.bounds);

zyhiang0909 回复于 2013年10月25日

3楼 @sycx 即使不用CGContextFillRect(UIGraphicsGetCurrentContext(), self.bounds);绘制出字体也是绿色的,我刚用CGContextFillPath(context);效果也是一样,问题就是出在我initWithFrame的时候没有设置这个view的背景颜色,代码的意图是一个定时器,然后绘制在view上,不加背景颜色的现象是2覆盖在1上,3,4,5....接着都是一个个覆盖上去的,我就是不知道为什么不设背景会出现这个效果。。。

sycx 回复于 2013年10月25日

UIView 有个属性opaque, 默认为 YES

UIView 还有个属性clearsContextBeforeDrawing, 默认为 YES

  • opaque=YES时, 系统调用-drawRect:前,不会清除以前内容
  • opaque= NO时, 系统调用-drawRect:前,会根据clearsContextBeforeDrawing属性做不同行为
    • clearsContextBeforeDrawing = YES, 则清除内容,以透明像素填充
    • clearsContextBeforeDrawing = YES, 则不清除内容

以上是context清理,之后是backgroundColor填充context,默认为nil,相当于不做任何操作;

当你指定一个颜色后,系统会用backgroundColor填充context, 自然就擦除了你之前的内容。

zyhiang0909 回复于 2013年10月25日

5楼 @sycx 原来如此,谢谢大神了!膜拜!!!

shifeng310 回复于 2013年10月27日

5楼 @sycx 真大神啊 ,

Ben.Zhong 回复于 2013年10月28日

5楼 @sycx 给力!

清醒疯子 回复于 2013年10月28日

5楼 @sycx

巨牛啊:)

morpheus1984 回复于 2013年10月28日

5楼 @sycx 想问下,当UIView 的属性 opaque=YES 时所产生的行为和当UIView的属性opaque=NoclearsContextBeforeDrawing = YES时所产生的行为一样 ,都是不会清除以前内容

登录 或者 注册
相关帖子