简体   繁体   中英

Change background color UIImage

I want to capture UIView and save as image. Here is my code

+ (UIImage *)captureView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0f);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];

//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
//    CGContextFillRect(context, view.bounds);

    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

It works fine. But I get one issue: I can not change background for that image. It always gets black background. So, how to change background?

Thanks.

//    [view drawViewHierarchyInRect:view.frame afterScreenUpdates:NO]; // comment this line

[view.layer renderInContext:UIGraphicsGetCurrentContext()]; // use this line

it gives the actual color of the view's as it is.. if your view's background color is clear color or black color, the image background color will be black color

The reason why you cannot change the background for a UIImage is because UIImage does not possess a background attribute. To add a background for which you can change color, you're going to have to create a custom UIView on your own for which the UIImage can be placed on top of. So for example, let's say you wanted to create a function which returns an image with a background of your choice:

- (UIImage* )setBackgroundImageByColor:(UIColor *)backgroundColor withFrame:(CGRect )rect{
    // tcv - temporary colored view
    UIView *tcv = [[UIView alloc] initWithFrame:rect];

    [tcv setBackgroundColor:backgroundColor];
    // set up a graphics context of button's size
    CGRectGSize gcSize = tcv.frame.size;
    UIGraphicsBeginImageContext(gcSize);

    // add tcv's layer to context
    [tcv.layer renderInContext:UIGraphicsGetCurrentContext()];

    // create background image now
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;

// [tcv release];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM