2

NSTimer関数から2秒ごとにsetNeedsDisplayInRectを呼び出しています。これは完璧に機能し、ランダムな位置にランダムな色で正方形を描画します。ただし、状況によっては、NSTimer関数で(forループを使用して)正方形をx回描画したいのですが、多数のエラーテストを行った後、setNeedsDisplayInRect x number ofを実行していても、drawRectが呼び出されるのは1回だけのようです。何回?私は一日中この問題を理解しようとしてきたので、私はいくつかの助けが欲しいです。カール。

以下の編集は私のコードです...

意見

- (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
このようにして、そのリストを反復処理し、描画ルーチンで各オブジェクトを描画できます。
オブジェクトの1つを追加/削除/変更するときはいつでも、setNeedsDisplay:

于 2010-01-07T19:28:49.510 に答える
0

自分自身を描画する機能を持つクラスを作成してから、必要な数のこのクラスのインスタンスを作成できます。

于 2010-01-07T23:20:35.347 に答える