始终调用drawRect绘图,但并不总是生成任何内容

时间:2012-02-29 20:22:23

标签: iphone cgcontext

我现在有一个奇怪的问题。我正在UIViewControllers UIView中生成一个绘图,它调用drawRect:,完成整个代码过程而不会崩溃但什么都不产生。如果我点击UIView内部的UI对象,则会重新加载drawRect并显示我的图像。

这是唯一的好处,它在每次首次加载时都会发生,但也会在一段时间后发生。

这通常有效,所以我错过了重装/设置功能吗?

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextClearRect(context, rect);
CGContextSetRGBFillColor(context, 1, 1, 1, 1.0f);
CGContextFillRect(context, rect);

CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor); 
CGContextSetLineWidth(context, 5.0);

CGContextMoveToPoint(context, 20, 20);
CGContextAddLineToPoint(context, 40, 40);   
CGContextStrokePath(context);

2 个答案:

答案 0 :(得分:1)

您的代码是否直接调用-drawRect:?如果是这样,停止。在调用-drawRect:之前,UIView设置绘图上下文,以便您的所有-drawRect:覆盖必须做的是绘制。如果您尝试直接调用该方法,则绘图上下文将无法正确设置,并且您的绘图将最终位于错误的位置,或者根本没有。当您让系统管理绘图时,绘图可以正常工作,在这种情况下,将在调用-drawRect:之前正确设置上下文。

答案 1 :(得分:-1)

听起来你的drawRect:代码没有被调用。请确保您根据需要在UIView上调用setNeedsDisplay