0

Is there way to create a UIImage or a UIImageView from a UIView with background color. My purpose is to get this color in the image. If it is possible, how can I do it?

3
  • So you want to create a view with a background colour just to get an image of that colour? (you only need a context for the image and draw the colour into that) What are you then going to use the image for? Commented Apr 30, 2014 at 13:09
  • you need to explain a little further about what you need exactly? Its quite absurd based on the details you provided Commented Apr 30, 2014 at 13:10
  • I think what you are asking is how to create a UIImage that's a specific color. Is this correct? Commented Apr 30, 2014 at 13:11

1 Answer 1

1
+ (UIImage *)imageWithColor:(UIColor *)color andRect:(CGRect)rect {
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Straight copy from stackoverflow.com/a/993159/525576 a 1px by 1px color is not going to be useful for him. Maybe pass the cgrect instead of predefine it.
I edited it so it can be passed to the function. I used the response from the link you passed for one of my current project ... so I'm sharing it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.