您的位置:首页 > 移动开发 > IOS开发

IOS 绘图的奇怪现象

2013-03-21 09:58 513 查看
最近应用需要自绘控件 但是在绘制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。效果如下

650) this.width=650;" src="http://img1.51cto.com/attachment/201303/152958533.png" border="0" alt="" />

上面的图显示 重新绘制的时候没有清空前面绘制的。
但是当[t setBackgroundColor:[UIColor clearColor]];后不停按Button效果如下

650) this.width=650;" src="http://img1.51cto.com/attachment/201303/153358210.png" border="0" alt="" />

如上图 重绘的时候会清除前面的绘图。所以有时候不一定要自己手动清空去 可能就是这点没注意。
(希望大神能解释这一现象的原因)。

本文出自 “做fashion的IT人” 博客,请务必保留此出处http://kyoworkios.blog.51cto.com/878347/1152536
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: