tags:

views:

111

answers:

2

Hello all,

I want something as follows

UIImage *solid = [UIImage imageWithColor:[UIColor darkGrayColor]];

to create an image with respect to some color.

how to do it in iPhone sdk.

A: 

You can draw the color into a CGContext and then capture an image from it:

- (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size {
  //Create a context of the appropriate size
  UIGraphicsBeginImageContext(size);
  CGContextRef currentContext = UIGraphicsGetCurrentContext();

  //Build a rect of appropriate size at origin 0,0
  CGRect fillRect = CGRectMake(0,0,size.width,size.height);

  //Set the fill color
  CGContextSetFillColorWithColor(currentContext, color.CGColor);

  //Fill the color
  CGContextFillRect(currentContext, fillRect);

  //Snap the picture and close the context
  UIImage *retval = UIGraphicsGetImageFromCurrentImageContext(void);
  UIGraphicsEndImageContext();

  return retval;
}
Louis Gerbarg
I think there is some method which makes it easy than drawing it.I saw it sometime while surfing but dint remember it. Thought of posting it here if anybody knows it.
rkb
Drawing it is ~7 lines you can wrap in a convenience method, I don't see it getting much easier, it is not exactly a common function.
Louis Gerbarg
A: 

If you're just trying to create a solid rectangle of colour why not just do something like

UIView *solid = [[UIView alloc] initWithFrame:someFrame];
solid.backgroundColor = [UIColor greyColor];

And then add the view to whatever subview you want to show the solid colour.

(That is, of course only if that's what you're trying to achieve. Maybe you aren't)

jbrennan