That Guy That Guy - 1 year ago 197
iOS Question

Xcode image slicing - stretch the outsides of the image but preserve an area in the centre

I want to use image slicing in Xcode to produce a resizable image with a central area that is held static. It seems that this is impossible in Xcode as it only allows for one stretched area and one shrunk area in each direction. Is this correct?

Resizable image

Does anyone know of a nice workaround for this? I need to use the image for a button so I can't do an arrangement of UIImageViews on top of each other unless I pass touches through and that gets a bit messy.

Many thanks.

Answer Source

As stretchableImageWithLeftCapWidth is deprecated with iOS 5.0, You can use resizableImageWithCapInsets. Check Apple Documentation, It states,

You use this method to add cap insets to an image or to change the existing cap insets of an image. In both cases, you get back a new image and the original image remains untouched. For example, you can use this method to create a background image for a button with borders and corners: when the button is resized, the corners of the image remain unchanged, but the borders and center of the image expand to cover the new size.

Another method is also available, resizableImage(withCapInsets:resizingMode:) if you want to set resizingMode

you can do something like,

    UIImage *image = [UIImage imageNamed:@"yourImageName"];

UIImage *streachedImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)];  //Edgeinsect that you want

// OR

UIImage *streachedImage2 = [image resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5) resizingMode:UIImageResizingModeStretch];

// OR

UIImage *streachedImage3 = [image resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5) resizingMode:UIImageResizingModeTile];

Check the Documentation for more details.

Update : (According to comment)

You need to just set backgroundImage and image both to your button. You can set image inset also to manage your image's position.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download