views:

28

answers:

1

Hi,

I want to create a blue rectangle image and see it in my view, but this code doesn't seem to work:

  CGRect imageRect = CGRectMake(50, 50, 64, 40);
  UIGraphicsBeginImageContext(imageRect.size);
  [[UIColor blueColor] set];
  UIRectFill(imageRect);
  UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  UIImageView *myImageView = [[UIImageView alloc] initWithImage:aImage];
  [self.view addSubview:myImageView]; 

Can someone fix it for me?

Thanks,

Sagiftw

+2  A: 

Your context is 64 points by 40 points. You filled a rectangle starting 50 points from the origin in a 40-point-tall context. That put it out of bounds, and anything you draw outside the bounds of the context won't show up.

Set your rectangle's origin to 0,0, which is the origin of the context. Then, your 64×40-point rectangle will be completely within the bounds of your 64×40-point context.

If you actually want to draw the rectangle 50 points below and to the right of the context's origin, then you need to make the context's size at least big enough to hold that margin plus the size of the rectangle. If you also want the same amount of margin on the other size, then the context's size should be the rectangle's size plus 100 points wide by 100 points tall (50 points on each side of the rectangle on each axis).

Peter Hosey
Thanks! I was so easy... :)