我每两秒从 NSTimer 函数调用 setNeedsDisplayInRect 一次。这工作得很好,并在随机位置绘制一个具有随机颜色的正方形。然而,在某些情况下,我想在 NSTimer 函数中绘制一个正方形 x 次(使用 for 循环) - 但是,经过多次错误测试后,即使我正在运行 setNeedsDisplayInRect x 次,drawRect 似乎也只被调用一次次?我希望得到一些帮助,因为我一整天都在试图解决这个问题。卡尔.
编辑下面是我的代码...
查看
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, currentColor.CGColor);
CGContextSetFillColorWithColor(context, currentColor.CGColor);
CGContextAddRect(context, redrawRect);
CGContextDrawPath(context, kCGPathFillStroke);
}
-(void)drawInitializer
{
int x = (int)arc4random() % [self.xCoordinates count];
int y = (int)arc4random() % [self.yCoordinates count];
self.currentColor = [UIColor randomColor];
self.redrawRect = CGRectMake ([[self.xCoordinates objectAtIndex:x] intValue], [[self.yCoordinates objectAtIndex:y] intValue], 25, 25);
[self setNeedsDisplayInRect:redrawRect];
}
Controller
- (void) handleTimer: (NSTimer *) timer
{
for(int i=0; i<5; i++)
{
[self.squareView drawInitializer];
}
}
最佳答案
您可以重构代码,以便拥有一个简单的类:
- 存储颜色
- 存储位置
- 有一种方法可以生成随机位置、颜色……
然后,您可以创建任意数量的实例并将它们推送到 NSMutableArray
中。
这样您就可以迭代该列表,并在绘制例程中绘制每个对象。
每当您添加/删除/修改某个对象时,请调用 setNeedsDisplay:
关于iPhone:drawRect 调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2022501/