Home / iPad

Drawing the view

Connecting the timer to the actual drawing of the display is the onTimer method. Take a good look at the code for this method (from the Listing 1-2), which starts with a new #pragma marker titled Animation:

#pragma mark -
#pragma mark Animation

- (void)onTimer{

  UILabel *fallingImageView = [[UILabel alloc]
 	  initWithFrame:CGRectMake(0, 0, 100, 30)];
  fallingImageView.text = fallingWords;
  fallingImageView.textColor = [UIColor purpleColor];
  fallingImageView.font = [UIFont systemFontOfSize:30];
  fallingImageView.backgroundColor = [UIColor clearColor];

  fallingImageView.adjustsFontSizeToFitWidth = YES;

  int startX = round(random() % 400);
  int endX = round(random() % 400);
  //speed of falling
  double randomSpeed = (1/round(random() % 100) +1) *speed;
  // image size;
  double scaleH = (1/round(random() % 100) +1) *60;
  double scaleW = (1/round(random() % 100) +1) *200;

  CGRect startImageFrame = fallingImageView.frame;
  CGRect endImageFrame = fallingImageView.frame;
  startImageFrame.origin = CGPointMake(startX, -100);
  endImageFrame = CGRectMake(endX, self.view.frame.size.
	    height,scaleW, scaleH);
  fallingImageView.frame = startImageFrame;
  fallingImageView.alpha = .75;
  [self.view addSubview:fallingImageView];

  [UIView animateWithDuration:randomSpeed
		    animations:^ {
	[UIView setAnimationDelegate:self];
	  fallingImageView.frame = CGRectMake(endX, self.
	    view.frame.size.height, scaleW, scaleH);
		}
	  completion:^(BOOL finished){
		  [fallingImageView
	    removeFromSuperview];
		  [fallingImageView release];
		}];
  }

The UILabel class implements a read-only text view. You can use this class to draw one or multiple lines of static text. In this case, the block of code uses the initWithFrame method with CGRectMake to create a rectangle, with the x-coordinate and y-coordinate of the rectangle's origin point at (0, 0) and a specified width and height (100, 30).

The code converts the fallingWords string to fallingImageView for display; sets up the text color, font, and background color; and adjusts the font size for the width. The font and textColor properties apply to the entire text string.

The next block of code uses the random function for the starting and ending points (startX and endX), for speed, and for width (scaleW) and height (scaleH) for fallingImageView. The random function uses a nonlinear additive-feedback random number generator, with a default table of size 31 long integers, and returns successive pseudo-random numbers in the range from 0 to 2,147,483,647. The code uses a CGRect structure for the location and dimensions of the rectangle, using CGPointMake to get the rectangle's origin point and using CGRectMake to build the rectangle. Then, addSub view adds a view so that it's displayed above its siblings.

[Previous] [Contents] [Next]