最近应用需要自绘控件 但是在绘制view的时候遇到一个现象。这个现象也许能让大家绘制控件的时候调bug少一些时间。

如我有一个UIView,实现如下

- (void)drawRect:(CGRect)rect

{

CGContextRef context=UIGraphicsGetCurrentContext();

CGContextSetStrokeColorWithColor(context, [UIColor yellowColor].CGColor);

CGContextMoveToPoint(context, X1, Y1);

CGContextAddLineToPoint(context, X2, Y2);

CGContextStrokePath(context);

}

然后我把这个绘制的UIview给一个ViewController。代码如下

- (void)viewDidLoad

{

[super viewDidLoad];

x1=20;

y1=10;

x2=120;

y2=30;

TX *t=[[TX alloc] init];

// [t setBackgroundColor:[UIColor clearColor]];

[t setBackgroundColor:nil];

self.view=t;

UIButton *bt=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 35)];

bt.backgroundColor=[UIColor yellowColor];

[bt addTarget:self action:@selector(btAction:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:bt];

}

-(void)btAction:(id)sender{

x1+=20;

y1+=20;

x2+=30;

y2+=30;

TX *t=(TX *)[self view];

t->X1=x1;

t->Y1=y1;

t->X2=x2;

t->Y2=y2;

[t setNeedsDisplay];

}

注意上面加红的两行代码。当[tsetBackgroundColor:nil];或者不设置BackgroundColor时默认也是nil的。然后不停的按Button。效果如下

上面的图显示 重新绘制的时候没有清空前面绘制的。

但是当[t setBackgroundColor:[UIColor clearColor]];后不停按Button效果如下

如上图 重绘的时候会清除前面的绘图。所以有时候不一定要自己手动清空去 可能就是这点没注意。

(希望大神能解释这一现象的原因)。