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

后端 未结 2 1406
傲寒
傲寒 2020-12-12 22:53

When using resizableImageWithCapInsets: to create an image for a UIButton only the normal state (the state set the image with using setBackgroundImage:forState:) works. All

相关标签:
2条回答
  • 2020-12-12 23:13

    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.)

    0 讨论(0)
  • 2020-12-12 23:30

    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];
    
    0 讨论(0)
提交回复
热议问题