2010年9月22日水曜日

Day6 Reaction Time(3)信号機画像を追加する

信号機ケーブル画像を追加する
画像をプログラミングで、表示したい位置に追加するために以下のように実装した。

UIImage* stopLightCableImage = [UIImage imageNamed:@"stopLightCable.png"];
 UIImageView* stopLightCableView = [[UIImageView alloc] initWithImage:stopLightCableImage];
 stopLightCableView.frame = CGRectMake(150, 0, stopLightCableImage.size.width, stopLightCableImage.size.height);
 stopLightCableView.image = stopLightCableImage;
 [self.view addSubview:stopLightCableView];

2行目
initWithImage メソッドで指定した画像で初期化する。

3行目
UIImageView の frame メソッドで表示位置を指定する。
→ bounds メソッドでは、stopLightCableView の、ローカルな座標の指定になるので間違い。frame メソッドで、親Viewから見た座標で位置を指定する。


4行目
image プロパティに画像を指定する。

信号機画像3種類をランダムに表示させるメソッドを実装する

以下の内容を訂正する。これではやりたかったことが実現できないので。。
訂正ここから-----------------------------------
以下のように実装した。
-(NSArray *)makeAnimationImagesArray{

 NSMutableArray* trafficLightArray = [NSMutableArray arrayWithObjects:
         [UIImage imageNamed:@"redLightSmall.png"],
         [UIImage imageNamed:@"yellowLightSmall.png"],
         [UIImage imageNamed:@"greenLightSmall.png"], nil];

 int count = [trafficLightArray count];
 srand([[NSDate date] timeIntervalSinceReferenceDate]);
 
 int i = 0;
 for(i=0; i<10; i++){
  NSUInteger pos1 = rand() % count;
  NSUInteger pos2 = rand() % count;
  
  [trafficLightArray exchangeObjectAtIndex:pos1 withObjectAtIndex:pos2];
 }
 
 return(trafficLightArray);
}
9行目 擬似乱数の発生系列を変更する種を、現在時刻から生成する。
10行目〜 0〜2をランダムに生成する。 訂正ここまで-----------------------------------


改めて、 信号機画像3種類を表示させる
次のメソッドを使用して、現行ループにタイマーとスケジュールを作成する。
scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
Creates and returns a new NSTimer object and schedules it on the current run loop in the default mode.
このメソッドで、3種類の画像(黄→赤→緑)を3秒おきに表示させる。
アクセルペダルをタップした時の動作を実装する 事前にフラグを持たせておいて、緑色画像が表示されたらフラグをONにする。また、その時の時刻を取得しておく。
次のメソッドを使用して、緑色画像が表示された時刻と、現在時刻の差を取得する。
timeIntervalSinceNow
Returns the interval between the receiver and the current date and time.

結果をUIAlertView で画面に表示する。