2

我每两秒从 NSTimer 函数调用 setNeedsDisplayInRect 。这完美地工作,并在随机位置绘制一个正方形,具有随机颜色。但是,在某些情况下,我想在 NSTimer 函数中绘制平方 x 次(使用 for 循环) - 但是,经过多次错误测试后,即使我正在运行 setNeedsDisplayInRect x number of次?我希望得到一些帮助,因为我整天都在试图解决这个问题。卡尔。

下面编辑是我的代码...

看法

- (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];
}

控制器

- (void) handleTimer: (NSTimer *) timer
{
    for(int i=0; i<5; i++) 
    {
         [self.squareView drawInitializer];
    }
}
4

2 回答 2

1

您可以重构代码,以便您拥有一个简单的类:

  • 存储颜色
  • 存储位置
  • 有一种方法来生成随机位置,颜色,......

然后,您可以根据需要创建任意数量的实例并将它们推送到NSMutableArray.
这样,您可以遍历该列表,并在您的绘图例程中绘制每个对象。
每当您添加/删除/修改您的一个对象时,请调用setNeedsDisplay:

于 2010-01-07T19:28:49.510 回答
0

您可以创建一个能够自行绘制的类,然后根据需要创建该类的尽可能多的实例。

于 2010-01-07T23:20:35.347 回答