Search code examples
iphoneiosobjective-cuiimageviewuiimage

UIImage with resizableimagewithcapinsets is distorted when trying to convert containing view to UIImage using [layer renderInContext:]


I have a view with this hierarchy:

-UIView -UIImageView -UILabel

UIImageView contains a UIImage with a resizable/stretchable image created with resizableimagewithcapinsets.

When I take a screenshot everything looks fine:

https://i.sstatic.net/uA6Lg.png

But when I try to capture the view to an UIImage the result is like this:

https://i.sstatic.net/IzUyS.jpg

As you can see the bottom of the stretched image looks funny.

This is the code I use to capture the view to an UIImage:

- (UIImage *) imageWithView:(UIView *)view
{
    [view setBackgroundColor:[UIColor whiteColor]];
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 2.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [view setBackgroundColor:[UIColor clearColor]];
    return img;
}

Note: The app will only be used in @2x devices.


Solution

  • It seems that resizableImageWithCapInsets: is problematic when trying to capture a view`s layer.

    Reverting back to the deprecated stretchableImageWIthLeftCapWidth:topCapHeight: method solved it. But doesn't feel right to revert back to a deprecated method, I'd be glad if anyone can solve the problem as is.