iPhone:drawRect调用一次

时间:2010-01-07 18:08:31

标签: iphone objective-c drawrect

我每两秒从一个NSTimer函数调用setNeedsDisplayInRect。这非常有效,并且可以随机抽取一个正方形的方块。但是,在某些情况下,我想在NSTimer函数中绘制一个平方x次(使用for循环) - 但是,经过多次错误测试后,似乎drawRect只被调用一次,即使我正在运行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];
    }
}

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

你可以创建一个能够绘制自己的类,然后创建你需要的这个类的多个实例。