Using resizableImageWithCapInsets: image for button only works for the state set, other states show a "gap" Using resizableImageWithCapInsets: image for button only works for the state set, other states show a "gap" ios ios

Using resizableImageWithCapInsets: image for button only works for the state set, other states show a "gap"


You aren't creating your insets properly for the image capping. I've reproduced your issue and corrected it by using the correct insets.

With your current code, you are creating caps of half of the image height and width - this leaves you with a "stretchable" area of 0x0 pixels - so you get nothing in the middle.

Why this isn't showing up as wrong in the normal state of the button I'm not sure - perhaps there is some optimisation built in to UIButton to fix things or auto-strectch if you don't supply a stretchable image, and this is not applied to the other states.

The caps are supposed to define the area of the image that must not be stretched. In the case of your button.png image, this is 6 pixels on the left and right sides, and 16 pixels in from the top and bottom. This isn't quite standard, you should tell your graphics designer that (at least for left-right which is the most common stretching) you should only have a 1px area in the centre, however this does not affect the outcome. If you do have a 1px stretchable area then you can standardise your code by deriving the caps from the image size as you have tried to do in your question (each cap is then (image.size.height - 1) / 2 for top/bottom, same but with width for left/right).

To get the correct images on your button, use the following code for creating the stretchable image:

UIEdgeInsets insets = UIEdgeInsetsMake(16, 6, 16, 6);image = [image resizableImageWithCapInsets:insets];


I was experiencing problems while using resizable images on iOS5 too. It turns out that if your button is of type "RountedRect" and you manipulate the background images, the resizable images will not behave as expected. (iOS6 handles this ok, presumably by assuming your new button type and adjusting as needed.)