天天看點

IOS 繪圖的奇怪現象

 最近應用需要自繪控件  但是在繪制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];

注意上面加紅的兩行代碼。當[t setBackgroundColor:nil];或者不設定BackgroundColor時預設也是nil的。然後不停的按Button。效果如下

IOS 繪圖的奇怪現象

上面的圖顯示 重新繪制的時候沒有清空前面繪制的。

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

IOS 繪圖的奇怪現象

如上圖 重繪的時候會清除前面的繪圖。是以有時候不一定要自己手動清空去  可能就是這點沒注意。

(希望大神能解釋這一現象的原因)。